UnboundLocalError: local variable 'x' referenced before assignment occurs when, inside a function, you use a variable before it is assigned, and Python has already decided that variable is local (because you assign to it somewhere in the function). Python does not fall back to a global or enclosing name once a name is treated as local. This guide explains why and how to fix it.

What this error means

When Python compiles a function, it marks a name as “local” if that name is assigned to anywhere in the function. When the function runs, every use of that name refers to the local variable. If the first use is before the first assignment (e.g. you read it, then assign to it), you get UnboundLocalError: local variable 'x' referenced before assignment. This is different from NameError, which happens when the name is not defined in any visible scope.

Common causes

  • Modifying a global inside a function. You use and then assign to a name that exists globally. Python treats it as local, so the “use” happens before the “assign” and triggers the error. Fix: declare global name if you really want to modify the global.
  • Conditional assignment. You assign to the variable only in an if branch but use it after the if. If the branch is not taken, the variable is never assigned. Fix: initialize the variable before the if, or in all branches.
  • Order of operations. You assign to the variable after using it (e.g. print(x) then x = 1). Fix: assign before use, or use a different variable for the value you need.

Example that causes the error

count = 0  # Global

def increment():
    print(count)   # UnboundLocalError: count is local (assigned below)
    count = count + 1

Fix 1: declare global

If you intend to read and update the global variable, declare it:

count = 0

def increment():
    global count
    print(count)
    count = count + 1

Fix 2: pass as parameter and return

Avoid global state by passing the value in and returning the new value:

def increment(current_count):
    return current_count + 1

count = 0
count = increment(count)

Fix 3: initialize before conditional use

def process(value):
    result = None  # Initialize so it's always defined
    if value > 0:
        result = value * 2
    print(result)

Next steps: Errors & Exceptions · NameError · Functions