Write Python. Understand every error.

Open the editor

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.

Try this code in Py-CRAFT

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

Learn the ideas behind it

Other common errors

Share this page: