[Tutor] Exception Handling
bob gailer
bgailer at gmail.com
Mon Dec 29 03:13:41 CET 2008
David wrote:
> David wrote:
>> Hi,
>> Is this the correct way to handle a ValueError exception and should I
>> get in the practice of catching them?
Well yes and no.
I think it is better to use the string method isdigit to test for digits
only.
Also IMHO it is bad design to put a lot of code inside a try block. In
this case the user might make a mistake on day and then is forced to
reenter the year and month!
Better to write a function for requesting an integer from the user which
loops until the user gets it right (with some way to escape if he gets
frustrated and just wants to quit.
>> Also any suggestions on the program.
>> thanks
>> -david
>>
> Might help if I included the program :)
>
> #!/usr/bin/python
> import time
>
> print "Enter year as 0000"
> print "Enter month and day as 00"
>
> 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)
>
> if mn - mnum:
> print "You are %i" % ynum, "years old."
> break
> elif mn == mnum and dy < dnum:
> print "You are %i" % ynum, "years old."
> break
> else:
> ret = int(ynum) - 1
> print "You are %i" % ret, "years old."
> break
> except ValueError:
> print "Oops, You must enter a number!"
>
>
>
--
Bob Gailer
Chapel Hill NC
919-636-4239
More information about the Tutor
mailing list