Handling UnboundLocalError
UnboundLocalError
is an exception that occurs when you try to reference a local variable that has not yet been assigned.
In Python, a variable declared inside a function is considered a
local variable
. Even if a variable with the same name is declared outside the function, it is considered a local variable within the function.
counter = 0 # Global variable
def increase_counter():
# UnboundLocalError occurs
counter += 1
return counter
print(increase_counter())
In the example above, the counter
global variable declared outside the function and the counter
local variable inside the increase_counter
function are recognized as different variables.
Therefore, when attempting to reference the counter
variable inside the function, an UnboundLocalError
exception occurs because the variable has not yet been assigned.
To use the counter
variable as a global variable in this example, you should use the global
keyword.
counter = 0 # Global variable
def increase_counter():
# Use as a global variable
global counter
counter += 1
return counter
print(increase_counter())
In the code above, the global
keyword is used to declare the counter
variable inside the increase_counter
function as a global variable.
How can you handle the UnboundLocalError exception?
One of the most common ways to handle an UnboundLocalError
exception is to use a try-except
block.
counter = 0 # Global variable
def increase_counter():
try:
counter += 1
except UnboundLocalError as e:
print(f'UnboundLocalError occurred: {e}')
return counter
print(increase_counter())
In the code above, when an UnboundLocalError
exception occurs while referencing the counter
variable inside the increase_counter
function, the except
block handles the exception and prints a message.
The UnboundLocalError
exception often occurs due to confusion between global and local variables, so be careful when referencing variables inside functions.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.