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
variable declared outside the function is global, but inside the increase_counter
function, it is treated as a separate local variable.
Therefore, when attempting to reference the counter
variable inside the function, an UnboundLocalError
is raised because the local variable is used before it has been assigned a value.
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
often results from confusion between local and global variables, so it is important to reference and modify variables carefully within functions.
UnboundLocalError occurs when a function references a local variable that is not initialized.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result