David Wakim
David Wakim

Reputation: 35

Trouble looping and avoiding crashing

I have been having trouble making this program loop... i want i to ask for the input if they give a string or a date in the wrong format...this is my code for it and i don't know why its not working. every time i run it and input a string, the first time it will say "Oops! That was not a valid date. Try again..." if the user inputs the wrong input again it crashes


THIS IS MY CODE.

while 1 == 1:
    try:
        birthday = raw_input("Enter your Birth date in MM/DD/YYYY format: ")
        birth_date = datetime.strptime(birthday, '%m/%d/%Y')

     except ValueError:
        print "Oops!  That was not a valid date. Try again..."
        birthday = raw_input("Enter your Birth date in MM/DD/YYYY format: ")
        birth_date = datetime.strptime(birthday, '%m/%d/%Y')

     if (((datetime.today() - birth_date).days)/365.2425) > 110:        
        print "Sorry You are older than 110 year i cannot do that math."

     elif ((datetime.today() - birth_date).days) < 0:
        print "Sorry you entered a date in the furture."

     elif ((datetime.today() - birth_date).days) == 0:
        print "OMG You were just born, tomorrow you will be one day old."
        else:
        print "Age: %d days " % ((datetime.today() - birth_date).days)

THIS IS THE ERROR IT SHOWS:

birth_date = datetime.strptime(birthday, '%m/%d/%Y')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'ASFA' does not match format '%m/%d/%Y'
logout

Upvotes: 1

Views: 48

Answers (3)

kylieCatt
kylieCatt

Reputation: 11039

Your code is formatted wrong:

while True:
    try:
        birthday = raw_input("Enter your Birth date in MM/DD/YYYY format: ")
        birth_date = datetime.strptime(birthday, '%m/%d/%Y')
        break
    except ValueError:
        print "Oops!  That was not a valid date. Try again..."

if (((datetime.today() - birth_date).days)/365.2425) > 110:        
    print "Sorry You are older than 110 year i cannot do that math."

elif ((datetime.today() - birth_date).days) < 0:
    print "Sorry you entered a date in the furture."

elif ((datetime.today() - birth_date).days) == 0:
    print "OMG You were just born, tomorrow you will be one day old."
else:
    print "Age: %d days " % ((datetime.today() - birth_date).days)

Your problem likely arose because you tried to put some more bad input into the code inside your except block. This exception would have been unhandled. You don't want to just "try again" inside your except. You want it to let the user know what was wrong and go back to the beginning. If they put some more bad input in that exception would be unhandled.

I took the rest of the code out of the while loop because I assume that is you intended. Your program would just run forever other wise. If you want that then you should use @NightShadeQueen's answer. I'm making the assumption that you just want the part that handles the exception to loop.

To have it running forever (at least until the user hits ctrl + c or you define some other way to exit) wrap it in a another while loop:

while True:
    while True:
        try:
            birthday = input("Enter your Birth date in MM/DD/YYYY format: ")
            birth_date = datetime.strptime(birthday, '%m/%d/%Y')
            break
        except ValueError:
            print("Oops!  That was not a valid date. Try again...") 

    if (((datetime.today() - birth_date).days)/365.2425) > 110:        
        print("Sorry You are older than 110 year i cannot do that math.") 

    elif ((datetime.today() - birth_date).days) < 0:
        print("Sorry you entered a date in the furture.") 

    elif ((datetime.today() - birth_date).days) == 0:
        print("OMG You were just born, tomorrow you will be one day old.") 
    else:
        print("Age: %d days " % ((datetime.today() - birth_date).days))

Although something more like this would likely be preferable:

def age_finder():
    while True:
        try:
            birthday = input("Enter your Birth date in MM/DD/YYYY format: ")
            birth_date = datetime.strptime(birthday, '%m/%d/%Y')
            break
        except ValueError:
            print("Oops!  That was not a valid date. Try again...") 

    if (((datetime.today() - birth_date).days)/365.2425) > 110:        
        print("Sorry You are older than 110 year i cannot do that math.") 

    elif ((datetime.today() - birth_date).days) < 0:
        print("Sorry you entered a date in the furture.") 

    elif ((datetime.today() - birth_date).days) == 0:
        print("OMG You were just born, tomorrow you will be one day old.") 
    else:
        print("Age: %d days " % ((datetime.today() - birth_date).days))

if __name__ == '__main__':
    try:
        while True:
            age_finder()
    except KeyBoardInterrupt:
        print()
        print('Thanks for using my app')
        exit()

This prevents the user form being shown the nasty looking error text when they hit ctrl + c.

Upvotes: 0

NightShadeQueen
NightShadeQueen

Reputation: 3334

Well, you have nothing to catch errors in your except block. You probably want that :P

Try:

while True: #Don't need 1==1, while True works too!
    try:
        birthday = raw_input("Enter your Birth date in MM/DD/YYYY format: ")
        birth_date = datetime.strptime(birthday, '%m/%d/%Y')

     except ValueError:
        print "Oops!  That was not a valid date. Try again..."
        #Because everything else is in an else block, now goes back
        #to start of loop
     else:
        #only happens if no exceptions happen
        if (((datetime.today() - birth_date).days)/365.2425) > 110:        
            print "Sorry You are older than 110 year i cannot do that math."
        #rest of your elif tree goes here, etc, etc.
        else: #I'm valid data! Finally!
            break
birth_date #do your calculations here, outside the loop?

Upvotes: 2

Victor Yan
Victor Yan

Reputation: 3509

The error occurs because the input data from raw_input "ASFA" does match the expected date time format '%m/%d/%Y'

Try inputting something like "01/20/1999" instead.

Upvotes: 0

Related Questions