[Tutor] Exception Handling
David
david at abbottdavid.com
Tue Dec 30 22:33:02 CET 2008
> On Mon, 29 Dec 2008 16:57:44 +0100, spir wrote:
>
>> > On Mon, 29 Dec 2008 09:10:45 -0000
>> > "Alan Gauld" <alan.gauld at btinternet.com> wrote:
>> >
>> >
>>> >> "bob gailer" <bgailer at gmail.com> wrote
>>> >>
>>>> >> > 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!
>>> >>
>>> >> Obviously there is no absolute rule here but I disagree. One of the
>>> >> biggest advantages of try/except error handling is that it keeps the
>>> >> mess of handling errors out of the main logic of the code. This has two
>>> >> effects:
>>> >> 1) Code that is much easier to read
>>> >> 2) a lot less error handling code
> Also, I'd rather ask for the dates in one raw_input, cuts much of the
> mess for the user (although it's a bit of extra codes)
Thank you all for the tips. Next to do is to get the dates in one
raw_input with the correct format and to check for a valid year, month,
and day. Here is what I have now;
#!/usr/bin/python
import time
curr_date = time.strftime("%Y %m %d", time.gmtime())
print "Please enter the date format as: ", curr_date
while True:
yr = raw_input("\nWhat year were you born? ")
mn = raw_input("What month were you born? ")
dy = raw_input("What day were you born? ")
try:
ynum = int(time.strftime("%Y", time.gmtime())) - int(yr)
mnum = int(time.strftime("%m", time.gmtime()))
dnum = int(time.strftime("%d", time.gmtime()))
except ValueError:
print "Oops, You must enter a number!"
else:
mn = int(mn)
dy = int(dy)
if mn <= mnum:
print "You are", ynum, "years old."
break
elif mn == mnum and dy < dnum:
print "You are", ynum, "years old."
break
else:
ret = int(ynum) - 1
print "You are", ret, "years old."
break
--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu
More information about the Tutor
mailing list