Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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 68,441 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))