← Back to Error Guide
UnboundLocalError

How to Fix UnboundLocalError

Raised when a local variable is referenced before it has been assigned.

What is UnboundLocalError?

An UnboundLocalError occurs when you try to use a local variable in a function before assigning a value to it. This often happens when a variable with the same name exists in the global scope, but you assign to it inside a function without declaring it as global; Python then treats it as a new local variable, which hasn't been given a value yet.

Common Causes

How to Fix

  1. If you intend to use the global variable inside the function, declare it as 'global' at the beginning of the function.
  2. Ensure that you assign a value to the variable before referencing it within the function.

Wrong Code


x = 10

def foo():
    print(x)  # UnboundLocalError here
    x = 5

foo()

Correct Code


x = 10

def foo():
    global x
    print(x)  # Works fine
    x = 5

foo()

More Python Error Guides