Error guide · Other errors
UnboundLocalError: cannot access local variable
A function used a variable that it also assigns to, before assigning it.
Example
count = 0 def add_one(): count = count + 1 add_one() print(count)
What Python says
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
If a function assigns to a name anywhere inside it, Python treats that name as local to the function. Reading it before the assignment fails, even if a global variable with the same name exists.
How to fix it
count = 0 def add_one(n): return n + 1 count = add_one(count) print(count)
Output: 1
Tips
- Pass values into functions as parameters and
returnthe result. - Avoid changing global variables from inside functions.