Local variable referenced before assignment
Production Risk
Common beginner mistake; Python compiles variable scope at parse time, not runtime.
A subclass of NameError raised when a local variable is referenced before being assigned a value. Python determines at compile time that a variable is local (because it is assigned in the function), so any reference before assignment fails.
- 1Assigning to a variable in a function while trying to use the outer-scope version before the assignment
- 2Conditional assignment where one branch never runs, leaving the variable undefined
- 3Augmented assignment (+=) on a variable that does not yet exist in local scope
A function assigns to a variable in one branch but reads it in another.
count = 10
def increment():
count += 1 # Python sees 'count' as local due to assignment
return count
increment()expected output
UnboundLocalError: local variable 'count' referenced before assignment
Fix 1
Use the global or nonlocal keyword
WHEN You intend to modify an outer scope variable
count = 10
def increment():
global count
count += 1
return countWhy this works
global tells Python to use the module-level variable rather than creating a local one.
Fix 2
Pass the value as a parameter and return it
WHEN Modifying an outer variable (preferred over global)
def increment(count):
return count + 1
count = 10
count = increment(count)Why this works
Passing values explicitly avoids shared mutable state and makes the function testable.
count = 10
def inc():
count += 1 # UnboundLocalError: local variable referenced before assignment
inc()try:
process()
except UnboundLocalError as e:
print(f"Variable scope issue: {e}")def inc(count):
return count + 1
count = 10
count = inc(count)✕ Overuse global variables
Global mutable state makes code hard to test and reason about; prefer parameters and return values.
Python Docs — Built-in Exceptions
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev