How to Fix - UnboundLocalError: Local variable Referenced Before Assignment in Python
Last Updated :
29 Mar, 2024
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 Access
- Global Variable Modification
Nested Function Variable Access
In 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.
Python3
def outer_function():
x = 10
def inner_function():
print(x) # Trying to access 'x' from the outer function
x = 20 # Inner function's local variable
print(x)
inner_function()
outer_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 Modification
In 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.
Python3
x = 5 # Global variable
def example_function():
x += 1
print(x)
example_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 Python
Below, are the approaches to solve “Local variable Referenced Before Assignment”.
- Global Variable Modification
- Nested Function Variable Access
Global Variable Modification
In 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.
Python3
x = 5
def example_function():
global x # Declare 'x' as global
x += 1 # Modify global variable 'x'
print(x)
example_function()
Nested Function Variable Access
In 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.
Python3
def outer_function():
x = 10
def inner_function():
nonlocal x # Declare 'x' as nonlocal
print(x) # Access 'x' from the outer function
x = 20 # Modify outer function's local variable 'x'
print(x)
inner_function()
outer_function()
Similar Reads
UnboundLocalError Local variable Referenced Before Assignment in Python Handling errors is an integral part of writing robust and reliable Python code. One common stumbling block that developers often encounter is the "UnboundLocalError" raised within a try-except block. This error can be perplexing for those unfamiliar with its nuances but fear not â in this article, w
4 min read
How to fix "SyntaxError: invalid character" in Python This error happens when the Python interpreter encounters characters that are not valid in Python syntax. Common examples include:Non-ASCII characters, such as invisible Unicode characters or non-breaking spaces.Special characters like curly quotes (â, â) or other unexpected symbols.How to Resolve:C
2 min read
Python | Accessing variable value from code scope Sometimes, we just need to access a variable other than the usual way of accessing by it's name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let's ta
3 min read
Accessing Python Function Variable Outside the Function In Python, function variables have local scope and cannot be accessed directly from outside. However, their values can still be retrieved indirectly. For example, if a function defines var = 42, it remains inaccessible externally unless retrieved indirectly.Returning the VariableThe most efficient w
4 min read
Variables under the hood in Python In simple terms, variables are names attached to particular objects in Python. To create a variable, you just need to assign a value and then start using it. The assignment is done with a single equals sign (=): Python3 # Variable named age age = 20 print(age) # Variable named id_number id_no = 4067
3 min read
Python program to create dynamically named variables from user input Given a string input, our task is to write a Python program to create a variable from that input (as a variable name) and assign it to some value. Below are the methods to create dynamically named variables from user input. Using globals() method to create dynamically named variables Here we are usi
2 min read
Python TabError: Inconsistent Use of Tabs and Spaces in Indentation Python, known for its readability and simplicity, enforces strict indentation rules to structure code. However, encountering a TabError can be frustrating, especially when the code appears to be properly aligned. In this article, we'll explore what a TabError is, and how to resolve TabError in Pytho
2 min read
SyntaxError: âreturnâ outside function in Python We are given a problem of how to solve the 'Return Outside Function' Error in Python. So in this article, we will explore the 'Return Outside Function' error in Python. We will first understand what this error means and why it occurs. Then, we will go through various methods to resolve it with examp
4 min read
Python | Using variable outside and inside the class and method In Python, we can define the variable outside the class, inside the class, and even inside the methods. Let's see, how to use and access these variables throughout the program. Variable defined outside the class: The variables that are defined outside the class can be accessed by any class or any me
3 min read
How To Fix Nameerror: Name 'Listnode' Is Not Defined NameError is a common issue in Python programming, and one specific instance is the "Name 'Listnode' is not defined" error. This error occurs when the interpreter encounters a reference to a variable or object named 'Listnode' that has not been defined in the current scope. In this article, we will
4 min read