W3docs

Python 3: UnboundLocalError: local variable referenced before assignment

This error occurs when you are trying to access a variable before it has been assigned a value.

This error occurs when you are trying to access a variable before it has been assigned a value. Here is an example of a code snippet that would raise this error:

Access a variable before it has been assigned a value in Python

def example():
    print(x)
    x = 5

example()

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

The error message will be:

UnboundLocalError - error message

UnboundLocalError: local variable 'x' referenced before assignment

In this example, the variable x is being accessed before it is assigned a value, which is causing the error. To fix this, you can either move the assignment of the variable x before the print statement, or give it an initial value before the print statement.

Give the variable an initial value before the print statement in Python

def example():
    x = 5
    print(x)

example()

or

Printing before determining the value in Python

def example():
    x = None
    print(x)
    x = 5

example()

Both will work without any error.