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.
Lessons in this chapter Β· Recursive and Lambda Functions
- 1. Functions That Call Themselves - Recursive Functions
- 2. Comparing Loop and Recursive Functions
- 3. Enhancing Recursive Function Efficiency with Memoization
- 4. Handling UnboundLocalError in Recursion
- 5. Multiple-choice quiz
- 6. Using Functions and Tuples Together
- 7. Functions within Functions - Callback Functions
- 8. Processing Sequences with filter() and map() Functions
- 9. Multiple-choice quiz
- 10. Creating Concise Anonymous Functions with Lambda
- 11. Calculating Fibonacci Sequence Using Lambda Functions
- 12. Coding Quiz - Extract Elements from List
- 13. Multiple-choice quiz
- 14. Fill-in-the-blank quiz
UnboundLocalError occurs when a function references a local variable that is not initialized.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help