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
Peyton Cook
835 PointsUnexpected exception with the python number game app?
My code works if I remove the .format() in the except block. Not sure where I went wrong?
from random import randint
random_number = randint(1, 10)
guesses_remaining = 3
# noinspection PyGlobalUndefined
def game():
global guess, guesses_remaining
while True:
try:
guess = int(input("{} guesses remaining. Guess a number between 1 and 10: ".format(guesses_remaining)))
except ValueError:
print("{} is not a number.".format(guess))
else:
if guess == random_number:
print("You got it! My number was {}".format(random_number))
again = input("Would you like to play again? y/n ")
if again.lower() == "y":
guesses_remaining = 3
continue
elif again.lower() == "n":
break
else:
print("That's not it")
guesses_remaining -= 1
if guess > random_number:
print("Too high!")
elif guess < random_number:
print("Too low!")
if guesses_remaining < 1:
print("Sorry, you ran out of guesses.")
break
continue
game()
1 Answer
Jennifer Nordell
Treehouse TeacherHi there! This is a tough question, but let's see if I can explain it. The biggest hint to what is going wrong is actually in the error you're receiving: NameError: name 'guess' is not defined.
Before you ever try to get the input from the user, the variable guess is undefined. It doesn't exist until the try block. And it's there that you try to convert it to an int and then assign it to guess. But if it fails to convert it to an int, then the assignment of a value to guess also fails. So when it hits the exception, the variable guess is undefined, which is why you can't format the string with it. But if we reorder your code just a tiny bit, it will work like I think you're expecting.
Note that I'm just showing the relevant part, but this is what I did:
while True:
guess = input("{} guesses remaining. Guess a number between 1 and 10: ".format(guesses_remaining)) #first get the input from the user and initialize guess
try:
guess = int(guess) #try to convert the guess to an integer
except ValueError:
print("{} is not a number.".format(guess)). #issue this error if it cannot be converted
Hope this helps!
Peyton Cook
835 PointsPeyton Cook
835 PointsThis makes perfect sense, thank you!