UnboundLocalError: Referenced Before Assignment
UnboundLocalError: local variable 'count' referenced before assignmentQuick Answer
You are reading a variable before assigning it in the same function. Python sees the assignment and treats it as local for the entire function. Use global or nonlocal if modifying an outer variable.
Why This Happens
Python determines scope at compile time. If a variable is assigned anywhere in a function, it is local for the entire function. Reading it before assignment raises this error even if it exists in an outer scope.
The Problem
count = 0
def increment():
count += 1
return countThe Fix
count = 0
def increment():
global count
count += 1
return count
# Or better, avoid globals:
def increment(count):
return count + 1Step-by-Step Fix
- 1
Use global or nonlocal
Add 'global varname' or 'nonlocal varname' at function top.
- 2
Pass as parameter
Pass the variable as a parameter and return the new value.
- 3
Initialize before use
Assign the local variable before any read operation.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free