Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Problem with the try method.

Hi everyone,

So in my script I use the 'try' method to check if the user input is an integer. This works every time except when the script first runs and I pass a non-int value on the very first guess. I get an unbound local error like this: "UnboundLocalError: local variable 'guess' referenced before assignment"

if I pass a non convertible int on any other try, the program works just fine. Anyone have any ideas?


1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 67,995 Points

It would help to see your code but based on your description, if it only fails for non-ints on the first pass then the try block is failing, the except block is run, and the else block, if present is skipped.

In this flow, if guess is only assigned in the try block, it will not yet have an assigned value for a non-int on the first pass. The first reference to guess after the try block will fail as you have seen.

One fix is to add guess = None in the except block or add the line above the try block to init guess.