UnboundLocalError: local variable referenced before assignment

Loading

The error message:

UnboundLocalError: local variable 'variable_name' referenced before assignment

occurs when you try to use a local variable inside a function before it has been assigned a value.


1. What Causes This Error?

This error mainly happens when Python assumes a variable inside a function is local, but it is not assigned before being used.

Example of the Error:

x = 10  # Global variable

def modify():
print(x) # Trying to use 'x' before assigning a value
x = x + 5 # Local assignment

modify()

Error Output:

UnboundLocalError: local variable 'x' referenced before assignment

Why Does This Happen?

  • Even though x is defined globally, Python treats x inside modify() as a local variable because it is being assigned (x = x + 5).
  • Since Python processes the function’s entire scope before execution, it marks x as a local variable.
  • The function tries to access x before it is assigned, leading to UnboundLocalError.

2. Solutions to Fix the Error

Solution 1: Use the global Keyword for Global Variables

If you want to modify a global variable inside a function, use the global keyword.

Corrected Code:

x = 10  # Global variable

def modify():
global x # Tell Python to use the global 'x'
print(x) # No error
x = x + 5 # Modify global 'x'

modify()
print(x) # Output: 15

Solution 2: Initialize the Variable Before Using It

If you don’t want to modify a global variable, ensure the variable is assigned before using it inside the function.

Incorrect Code:

def example():
print(y) # Error: 'y' is used before assignment
y = 20 # Local assignment

example()

Corrected Code:

def example():
y = 20 # Define before using
print(y) # No error

example()

Solution 3: Use nonlocal for Variables Inside Nested Functions

If a variable is inside an outer function, but you need to modify it inside an inner function, use nonlocal.

Incorrect Code:

def outer():
x = 5 # Local to 'outer'

def inner():
x = x + 1 # Error: Python thinks 'x' is local
print(x)

inner()

outer()

Corrected Code:

def outer():
x = 5 # Local to 'outer'

def inner():
nonlocal x # Use 'x' from 'outer'
x = x + 1
print(x)

inner()

outer() # Output: 6

Solution 4: Use Default Arguments to Avoid Scope Issues

You can pass the variable as a function parameter to avoid scope confusion.

Corrected Code:

x = 10

def modify(x): # Pass 'x' as a parameter
x = x + 5
print(x)

modify(x) # Output: 15
print(x) # Global 'x' is still 10

Leave a Reply

Your email address will not be published. Required fields are marked *