![]() |
Developers often encounter the UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches. What is UnboundLocalError: Local variable Referenced Before Assignment?This error occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution. Syntax: UnboundLocalError: local variable 'x' referenced before assignment Below, are the reasons by which UnboundLocalError: Local variable Referenced Before Assignment error occurs in Python:
Nested Function Variable AccessIn this code, the outer_function defines a variable ‘x’ and a nested inner_function attempts to access it, but encounters an UnboundLocalError due to a local ‘x’ being defined later in the inner_function.
Output Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 12, in <module>
outer_function()
File "Solution.py", line 10, in outer_function
inner_function()
File "Solution.py", line 5, in inner_function
print(x) # Trying to access 'x' from the outer function
UnboundLocalError: local variable 'x' referenced before assignment Global Variable ModificationIn this code, the function example_function tries to increment the global variable ‘x’, but encounters an UnboundLocalError since it’s treated as a local variable due to the assignment operation within the function.
Output Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 7, in <module>
example_function()
File "Solution.py", line 4, in example_function
x += 1 # Trying to modify global variable 'x' without declaring it as global
UnboundLocalError: local variable 'x' referenced before assignment Solution for Local variable Referenced Before Assignment in PythonBelow, are the approaches to solve “Local variable Referenced Before Assignment”.
Global Variable ModificationIn this code, example_function successfully modifies the global variable ‘x’ by declaring it as global within the function, incrementing its value by 1, and then printing the updated value.
Output 6 Nested Function Variable AccessIn this code, the outer_function defines a local variable ‘x’, and the inner_function accesses and modifies it as a nonlocal variable, allowing changes to the outer function’s scope from within the inner function.
Output 10 20 |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |