UnboundLocalError: cannot access local variable
UnboundLocalError: cannot access local variable in Python means you assigned to a name somewhere inside a function, which made it local for the whole function — including before the assignment runs.
How do I fix UnboundLocalError: cannot access local variable?
To fix UnboundLocalError: cannot access local variable in Python, locate the line causing the error and check the values right before it runs. Most occurrences happen because of modifying a global without declaring it. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does UnboundLocalError: cannot access local variable mean?
Python decides local versus global when it compiles the function, not while it runs. If a name is assigned anywhere in the body, every reference to it in that function is local. Reading it before the assignment executes raises UnboundLocalError, even if a module-level variable of the same name exists.
Why does UnboundLocalError: cannot access local variable happen?
1. Modifying a global without declaring it
total += n is a read then a write, and the read happens against an unassigned local.
Breaks
total = 0
def add_all(nums):
for n in nums:
total += n
return totalWorks
def add_all(nums):
running = 0
for n in nums:
running += n
return running2. A variable only assigned inside an if
If the branch never runs, the name was never bound, and the return line fails.
Breaks
def last_even(nums):
for n in nums:
if n % 2 == 0:
found = n
return foundWorks
def last_even(nums):
found = None
for n in nums:
if n % 2 == 0:
found = n
return foundHow to find it in your own code
Initialise before the loop or branch so the name exists on every path. Using `global` works but leaves the function stateful across calls — a local accumulator is almost always the better fix.
Try it: fix this bug
easylast_even([1, 3]) crashes: UnboundLocalError: cannot access local variable 'found' where it is not associated with a value.
def last_even(nums):
for n in nums:
if n % 2 == 0:
found = n
return foundMore challenges with this error
Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser — no install, no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.