Python UnboundLocalError Exception
Example
An UnboundLocalError occurs if a function uses a local variable before it gets a value:
x = 5
def myfunc():
print(x)
x = 10
myfunc()
Try it Yourself »
Definition and Usage
The UnboundLocalError exception occurs when you use a local variable in a function before it gets a value.
In the example, x = 10 makes x a local variable in the whole function. So print(x) cannot use the global x, and the local x does not have a value yet.
Tip: Use the global keyword if you want to change a global variable inside a function.
Exception Handling
Example
Handling the UnboundLocalError in a try...except statement:
x = 5
def myfunc():
print(x)
x = 10
try:
myfunc()
except UnboundLocalError:
print("The variable does not have a value yet")
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.