← All Python errors

Python error explained

UnboundLocalError: what it means and how to fix it

A function changes a variable it can only see from outside.

The message

UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

What it means

If a function assigns to a name anywhere inside it, Python treats that name as local to the function. So count += 1 tries to read a local count that has not been set yet. The cleanest fix is to pass values in and return the result.

Common causes

  • Changing a global variable inside a function
  • A counter or total kept outside the function that uses it

Example that raises it

count = 0

def add_point():
    count += 1

add_point()
add_point()
print("Points:", count)

The fix

count = 0

def add_point(count):
    return count + 1

count = add_point(count)
count = add_point(count)
print("Points:", count)

Tip: Pass values into functions and return new ones. You can use the global keyword, but code that avoids it is easier to test and reason about.

Fix the broken version yourself in the editor on this page. It runs real Python in your browser.

Start the free lessons More Python errors