ShareYourGroupShareYourGroupError Explainer

Python UnboundLocalError: local variable referenced before assignment

A plain-words explanation of this Python message: what it means, the usual causes, and the steps that fix it.

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

Make the error yourself

Run with Python 3.14.10. This is the smallest example we could find that shows it.

Python program (main.py)

count = 0

def add_one():
    count = count + 1
    return count

print(add_one())

Output (the real message)

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(add_one())
          ~~~~~~~^^
  File "main.py", line 4, in add_one
    count = count + 1
            ^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

Why it happens

Inside a function, any name that you assign to is treated as a local variable for the whole function. In the example count = count + 1 assigns to count, so Python decides count is local, and then it cannot read the value before it has been given one. The global count outside is not used. Older Python versions word the same error as "local variable 'count' referenced before assignment".

How to fix it

  1. Best: pass the value in as an argument and return the new value, as in the fixed code.
  2. Or declare global count at the top of the function. It works, but it makes programs harder to follow.
  3. For state that changes, use a class or a dictionary instead of loose globals.

The corrected version

Python program (main.py)

count = 0

def add_one(value):
    return value + 1

count = add_one(count)
print(count)

Output (the corrected version)

1

How to avoid it

Avoid changing global variables from inside functions. Functions that take inputs and return outputs are easy to test.

Questions

Why can I read a global inside a function but not change it?

Reading finds the name in the outer scope. Assigning creates a new local name unless you declare it global (or nonlocal for an enclosing function).

This is an independent guide. It is not connected with Python, Microsoft, Google, GitHub or the Git project. Product names belong to their owners. Examples were run on 13 November 2026 in a practice folder or a blank workbook; your version may word a message slightly differently.