Jervis Whitley wrote:


On Wed, Dec 31, 2008 at 8:33 AM, David <da...@abbottdavid.com <mailto:da...@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.ga...@btinternet.com
            <mailto:alan.ga...@btinternet.com>> wrote:
             > >

                 >> "bob gailer" <bgai...@gmail.com
                <mailto:bgai...@gmail.com>> wrote
                 >>

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!")

WOW, thanks Jervis, I had to edit some of my mistakes to get it to work right if your birthday is today. I also looked at tm_year, tm_mon, and tm_day. I still need to get it to prduce an error if the year is 0 or 2009, the month is 0 or 13 and the day is 0 or 32.
david [06:56 PM] opteron ~ $ ./py_get_age.py
Please enter the date format as:  2008 12 30

What year were you born? 2010
What month were you born? 14
What day were you born? 34
You are -3 years old.

Here is a link to the current program;
http://dwabbott.com/code/
Thanks again everyone,
-david


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to