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. Here is an example of a code snippet that would raise this error:
def example():
print(x)
x = 5
example()
Watch a video course
Python - The Practical Guide
The error message will be:
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.
def example():
x = 5
print(x)
example()
or
Both will work without any error.