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
Valerio Versace
11,319 Pointstry except else bug in Number Game Refinement program in Python Basics
I think I found a bug in the Number Game Refinement program in Python Basics.
Kenneth suggets the following code:
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:
#game stuff happens
Now when I try to input a non-number as my first input, I get an error saying that local variable guess is referenced before being assigned. That's because parsing my input as int fails so guess gets no value... but the except references it. For this same reason, if I input any number (say 2) and then input a letter (say "a"), the output will be "2 isn't a number!" because the variable guess still has 2 as a value.
This is how I changed it:
while len(guesses) < 5:
guess = input("Guess a number between 1 and 10: ")
try:
guess = int(guess)
except ValueError:
print("{} isn't a number!".format(guess))
else:
#game stuff happens
This way I'm going to get the input from the player regardless; if Python can parse it to an int then we are fine; otherwise we catch the exception, parse it to string and print the message to the player.
Craig Bell
565 PointsThanks Valerio, was going to post a question as I had the same issue. Appreciate it
Chris Freeman
Treehouse Moderator 68,468 PointsChris Freeman
Treehouse Moderator 68,468 PointsGood catch! (pardon the pun). Tagging Kenneth Love for feedback.