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
Iskander Ismagilov
13,298 PointsNameError: Try and except
def game():
try:
new = int(input())
except ValueError:
print("{} isn't int".format(new))
game()
game()
When I run this script and inputing a string or float, it gives me: "UnboundLocalError: local variable 'new' referenced before assignment"
Wasn't assignment before referencing as an input?
And how to print the wrong input without an error?
1 Answer
Alfonso Concha
3,773 PointsWhen you use Try and Except, if the Try block result in an exception the code inside it wont get executed and instead the Except block gets executed. So in the script you have, when you dont provide a valid Int for new, that code doesnt get executed so the Print call inside the Except block doesnt know what New is, and it gets a UnboundLocalError. You should save the input as a string and then have a Try and Except block.
Iskander Ismagilov
13,298 PointsIskander Ismagilov
13,298 PointsThank you!