Skip to content

UnboundLocalError: local variable 'x' referenced before assignment

Error message

                local variable 'x' referenced before assignment
              

Quick summary

You referenced a local variable before assigning a value to it, usually due to a conditional assignment path.

Why this happens

  • Using a variable in a branch where it wasn't assigned

  • Assigning to a variable only in an if block, then using it outside

  • Forgetting to initialize a variable before a loop

Minimal example

✗ Broken code
def classify(n):
    if n > 0:
        result = "positive"
    elif n < 0:
        result = "negative"
    return result  # UnboundLocalError if n == 0

classify(0)
✓ Fixed code
def classify(n):
    if n > 0:
        result = "positive"
    elif n < 0:
        result = "negative"
    else:
        result = "zero"
    return result

classify(0)  # 'zero'

The else branch was missing, so result was unassigned when n == 0. Adding the else branch ensures all paths assign result.

How to diagnose

  • Check all code paths that assign to the variable

  • Ensure the variable is assigned before any use

  • Look for conditional assignments that might not execute

How to fix

  • Initialize the variable before the conditional block

  • Ensure all code paths assign the variable

  • Use a default value at the start of the function

How to prevent

  • Initialize variables at the top of functions

  • Ensure all branches assign to variables used later

Related Resources

Related Glossary

Related Lessons

← Back to language