Python Forum

Full Version: Error Handling is weird
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So, I have a try/except sequence to make sure my program doesn't get bogged by a user entering a non-number in response to a prompt asking for a number. Oddly enough, when it gets a non-number, it prints my message I have set up as the action for the "except" twice rather than once. Why is it repeating the try twice?

import random

def game (theNumber, newNumber):
    try:
        int(newNumber)
    except:
        print("That's not going to work. I need a number from 0 to 10.")
        return False, False, theNumber

    myNumber = int(newNumber)
    if myNumber >= 11 or myNumber < 0:
        print("I said 0 to 10. Let's try again:")
        return 
    elif theNumber == myNumber:
        return True, True, theNumber
    else:
        return True, False, theNumber

while True:
    
    doYou = input("Would you like to play? ")
    if doYou == "Yes":
        theNumber = random.randrange(0,10)
        newNumber = input("Guess a number from 0 to 10. ")
        game(theNumber, newNumber)
    else:
        print("Consent is vital, I need a clear answer: Yes")

    myResult = game(theNumber, newNumber)

    #print(myResult[0])
    #print(myResult[1])

    if myResult[0] == False:
        continue

    if myResult[1] == False:
        print("Nope, the answer was", theNumber)
    elif myResult[1] == True:
        print("Congratulations, you guessed it:", theNumber)
    else:
        continue
You are calling game inside your if block and outside so all that code runs twice on yes and once on no:
It should instead be only called once, but let's look a little more at your input validation.  Firstly never catch a naked except.  In this case the exception you want is ValueError
Here is a look at a more elegant way to do this:
This function will loop every time it gets an invalid input, instead of just looping the whole program.

This is an organized rewrite of what you have so far.  Obviously try to learn from it what you can rather than simply copy it: