Python Python Basics (2015) Number Game App Number Game Refinement

jasper printemps
jasper printemps
4,398 Points

help with number game

Traceback (most recent call last):
  File "C:\Users\jasper\Desktop\pycharm scripts\number_game.py", line 46, in <module>
    number_game()
  File "C:\Users\jasper\Desktop\pycharm scripts\number_game.py", line 15, in number_game
    print("{} That's not a number!".format(guess))
UnboundLocalError: local variable 'guess' referenced before assignment
import random
guesses =[]
def number_game():
    print("""Welcome to the number game
    """)
    #generate a random number between 1 and 10
    secret_num = random.randint(1, 10)
    tries = 5

    while len(guesses) < 5:
        try:#get a number guess from the player
             guess = int(input("Guess a number between 1 and 10: "))

        except ValueError :#catch when someone submits a non integer
             print("{} That's not a number!".format(guess))

        else :
             tries -= 1
             #compare guess to secret number
             if guess == secret_num:
                 print("You got it! my number was {}".format(secret_num))
                 break

            # limit the number of guesses

             elif input == "RESTART":
                number_game()
                #print hit/miss
             else:
                print("That's not it!")
                # print "to low" or "to high" messages for bad guesses
                if guess < secret_num:
                    print("To low {} tries left ".format(tries))
                elif guess > secret_num:
                    print("To high {} tries left ".format(tries))
             guesses.append(guess)
    else:
        print('''To bad my number was {}

        Thanks for playing'''.format(secret_num))
    play_again =input('Do you want to play again Y/n')
    if play_again.lower != "n":
        number_game()
    else:
        print("Bye!")
number_game()
# let people play again

[MOD: added ```python formatting -cf]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 58,945 Points

The "guess referenced before assignment" is from the try statement failing. If there are any errors in the try block before guess is fully assigned, it will have no value: it will be undefined. When the except block runs, there isn't a value for guess to be used in the string format.

One fix is to capture the user input separately from the conversion. This allows saving the input for the string format should it fail in the int() conversion:

        try:#get a number guess from the player
             guess = input("Guess a number between 1 and 10: ")
             guess = int(guess)  # <-- if this fails, guess will still have input value
        except ValueError :#catch when someone submits a non integer
             print("{} That's not a number!".format(guess))