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

Daniel Egelund
Daniel Egelund
2,970 Points

Bug in code showed in the video

If you run the game and enter a letter(or something that is not an integer) as your first guess, you get a syntax error.

Try downloading the code, run the game and enter a letter.

Chris Freeman
Chris Freeman
Treehouse Moderator 59,735 Points

What error do you get? are you running locally in Python2 or Python3?

Andy McMurry
Andy McMurry
4,276 Points

Traceback (most recent call last):
File "number_game.py", line 27, in <module>
game()
File "number_game.py", line 15, in game
print("{} isn't a number!".format(guess))
UnboundLocalError: local variable 'guess' referenced before assignment

That's what I've been getting, here's my code:

import random

def game():
  #generate a random number between 1 and 10

  secret_num = random.randint(1,10)
  guesses = []

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

      except ValueError:
          print("{} isn't a number!".format(guess))

      else:

          if guess == secret_num:
            print("You got it, way to go!!")
            break

          else:
            print("That's not it, try again...")      
      guesses.append(guess)

game()

1 Answer

Steven Pozega
Steven Pozega
14,926 Points

The guess variable isn't being set when you enter something other than an int. Set the variable first, then try to convert it to an int. Like this:

guess = input("Guess a number between 1 and 10: ")

try:
    guess = int(guess)
except ValueError:
    print("{} is not an acceptable value".format(guess))
    continue

The print() function is probably where the error getting thrown. When you try to format guess into the string, python couldn't find a variable with that name because it didn't bother storing the value in memory once it realized it can't be converted to an int.