[Tutor] Exception Handling
Alan Gauld
alan.gauld at btinternet.com
Mon Dec 29 10:02:29 CET 2008
"David" <david at abbottdavid.com> wrote
>> Is this the correct way to handle a ValueError exception and should
>> I get in the practice of catching them?
Yes and Yes.
Although I woulfd move the except clause up to just after the input
section
(which is where the errors will be raised). A couple of other comments
below:
> while True:
> try:
> yr = int(raw_input("What year were you born? "))
> mn = int(raw_input("What month were you born? "))
> dy = int(raw_input("What day were you born? "))
> curr_date = time.strftime("%Y %m %d", time.gmtime())
>
> ynum = int(time.strftime("%Y", time.gmtime())) - int(yr)
> mnum = int(time.strftime("%m", time.gmtime()))
> dnum = int(time.strftime("%d", time.gmtime()))
> mn = int(mn)
> dy = int(dy)
Put the except here, its easier to see where the error came from.
And since the error message only applies to these int() calls its
more accurate.
> if mn - mnum:
> print "You are %i" % ynum, "years old."
This is an odd use of string formatting, more usually you
would only use one string:
print "You are %i years old" % ynum
Either that or just insert the value and not use formattting:
print "You are", ynum, "years old."
> else:
> ret = int(ynum) - 1
You don't need the int conversion here since yuou already
did it at the input stage. But...
> print "You are %i" % ret, "years old."
Why not just
print "You are %i" % ynum-1, "years old."
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list