[Tutor] Exception Handling

Jervis Whitley jervisau at gmail.com
Tue Dec 30 23:12:09 CET 2008


On Wed, Dec 31, 2008 at 8:33 AM, David <david at abbottdavid.com> wrote:

>  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
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Hi David,

If the user enters incorrect data for the month or day, a ValueError will
still be raised
on the conversion to integer.

I suggest that you wrap your request for user information in a function that
does the checking
for you. You can re-use this function for each piece of integer information
you require from the user.

example:

import time


class BadUserError(Exception):
    pass

def get_integer(retrieve, question, attempts=3):
    """
    A small function to attempt to retrieve
    information from a user, given a prompt question.

    retrive - any function that will accept a string as an argument
                and return a string or otherwise response from the user.
    question - a string type question that you would like to ask the user to
                respond to.
    attempts[optional] - how many times the user can incorrectly
                        enter data before the BadUserError is raised.
    """

    while attempts > 0:
        num = retrieve(question)
        try:
            # try casting the user input as an integer.
            return int(num)
        except ValueError:
            print "Oops, You must enter a number!"

        attempts -= 1
    raise BadUserError("Too many incorrect tries!")

curr_date = time.strftime("%Y %m %d", time.gmtime())
print "Please enter the date format as: ", curr_date


yr = get_integer(raw_input, "\nWhat year were you born? ")
mn = get_integer(raw_input, "What month were you born? ")
dy = get_integer(raw_input, "What day were you born? ")

today = time.gmtime()

ynum = today.tm_year - yr
mnum = today.tm_mon
dnum = today.tm_mday

if mn <= mnum:
    print "You are", ynum, "years old."
elif mn == mnum and dy < dnum:
    print "You are", ynum, "years old."
else:
    ret = int(ynum) - 1
    print "You are", ret, "years old."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081231/78fd40ce/attachment.htm>


More information about the Tutor mailing list