BugHunt

UnboundLocalError: cannot access local variable

You assigned to a name somewhere inside a function, which made it local for the whole function — including before the assignment runs.

PythonScope and closure bugs

What it means

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.

Common causes

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 total

Works

def add_all(nums):
    running = 0
    for n in nums:
        running += n
    return running

2. 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 found

Works

def last_even(nums):
    found = None
    for n in nums:
        if n % 2 == 0:
            found = n
    return found

How 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.

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.

Other common errors