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 trialDaniel Egelund
9,702 PointsBug 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.
Andy McMurry
4,276 PointsTraceback (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
14,926 PointsThe 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.
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsWhat error do you get? are you running locally in Python2 or Python3?