How to Fix: UnboundLocalError: local variable referenced before assignment

3D illustration of a robot trying to use a tool before it has been delivered, representing the UnboundLocalError in Python.

This is one of Python’s trickiest errors, known as UnboundLocalError. It happens because of how Python handles Variable Scope (where variables can be seen).

The Scenario

You have a variable outside a function, and you try to change it inside the function. This is where the UnboundLocalError often appears.

Problem Code:

score = 0

def increase_score():
    # We try to use the 'score' from outside
    score = score + 10
    print(score)

increase_score()
# CRASH! UnboundLocalError: local variable 'score' referenced before assignment

Why it fails

When Python sees score = ... inside the function, it assumes score is a new local variable just for that function. But then it sees the right side of the equation: = score + 10. It tries to find this “new local” score, realizes it hasn’t been created yet, and crashes, leading to an UnboundLocalError.

The Fix: The global Keyword

You must explicitly tell Python: “I’m not making a new variable; I want to use the global one.”

score = 0
def increase_score():
    global score  # <--- This is the magic line
    score = score + 10
    print(score)
increase_score()
# Output: 10 (Success!)

Pro Tip: Try to avoid global variables if possible! It’s usually better to pass the value in as an argument and return the new value, which helps in preventing an UnboundLocalError.

Similar Posts

Leave a Reply