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

Python Python Basics Functions and Looping Expecting Exceptions

Austin Jung
Austin Jung
1,311 Points

Try/Except statement scope

I have some experience in Java, and I know that writing code to catch exceptions similar to what's shown in the video in Java would also present a scope issue since total_due is declared within the try statement.

Does the same apply to Python? Would total_due still be inaccessible before moving the amount_due line into an else statement?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Answering a slightly different question: The value total_due is accessible if and only if an error isn't raised during the input or float execution. If no error is raised, then total_due is available immediately.

Post back if you have more questions. Good luck!!

Austin Jung
Austin Jung
1,311 Points

I guess a better way of phrasing my question would have been "Is total_due usable outside of the try/except/else blocks?"

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Since the assignment to total_due is not assigned within a function or class, it is in the namespace scope of the entire file check_please.py. This makes it accessible as a global variable anywhere within the file.

Here's a short review of python scoping rules: https://stackoverflow.com/a/292502/2088339

Austin Jung
Austin Jung
1,311 Points

Got it, thank you!