UnboundLocalError is a subclass of NameError raised when a local variable is referenced before it has been assigned a value. Python determines variable scope at compile time: if a name is assigned anywhere in a function, it is treated as local throughout that function.
Why it happens
- •A variable is assigned inside a function but read before the assignment line is reached.
- •An augmented assignment (+=, -=) on a name that exists in the enclosing scope but not locally.
- •A conditional branch assigns the variable only sometimes, but it is read unconditionally.
- •Using the same name for both a local variable and a parameter in a confusing way.
Examples
Code that triggers the error
count = 0
def increment():
count += 1 # reads count before assigning
increment()Error output
UnboundLocalError: local variable 'count' referenced before assignment
How to fix it
Declare the variable with global (for module-level) or nonlocal (for enclosing function scope) before modifying it. Alternatively, pass the value as a parameter and return the new value instead of mutating outer state.
Fixed code
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free