This guide explains nameerror and unboundlocalerror explained through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
NameError occurs when a name cannot be resolved. UnboundLocalError is a more specific error when a function treats a name as local but reads it before the local value has been assigned.
When and Why to Use It
The following example focuses on a practical use of NameError and UnboundLocalError Explained.
Step-by-Step Example
score = 10
def broken_score():
try:
print(score)
score = 20
except UnboundLocalError as error:
print(type(error).__name__)
broken_score()
Understanding the Example
Because score is assigned in the function, Python classifies it as local throughout that function; reading it first raises UnboundLocalError.
Expected Output
UnboundLocalError
Important Behavior and Edge Cases
Do not solve this by adding global automatically. Prefer passing the score into the function and returning a result.
Try It Yourself
Rewrite broken_score so it accepts the initial score as a parameter.
Common Beginner Mistakes
- Do not solve this by adding global automatically. Prefer passing the score into the function and returning a result.
- Handling the symptom rather than identifying the failing operation, or letting a broad exception handler hide defects.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- NameError occurs when a name cannot be resolved.
- Because score is assigned in the function, Python classifies it as local throughout that function; reading it first raises UnboundLocalError.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.