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 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 67,909 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 67,909 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!