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:
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
How To Fix - Python RuntimeWarning: overflow encountered in scalar
One such error that developers may encounter is the "Python RuntimeWarning: Overflow Encountered In Scalars". In Python, numeric operations can sometimes trigger a "RuntimeWarning: overflow encountered in a scalar." In this article, we will see what is Python "Python Runtimewarning: Overflow Encount
3 min read
Different Forms of Assignment Statements in Python
We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object. There are some important properties of assignment in Python :-
3 min read
Python Program to Find and Print Address of Variable
In this article, we are going to see how to find and print the address of the Python variable. It can be done in these ways: Using id() functionUsing addressof() functionUsing hex() functionMethod 1: Find and Print Address of Variable using id()We can get an address using id() function, id() functio
2 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
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 (=): C/C++ Code # Variable named age age = 20 print(age) # Variable named id_number id_no = 4
3 min read
How to Change Class Attributes By Reference in Python
We have the problem of how to change class attributes by reference in Python, we will see in this article how can we change the class attributes by reference in Python. What is Class Attributes?Class attributes are typically defined outside of any method within a class and are shared among all insta
3 min read
Python program to find number of local variables in a function
Given a Python program, task is to find the number of local variables present in a function. Examples: Input : a = 1 b = 2.1 str = 'GeeksForGeeks' Output : 3 We can use the co_nlocals() function which returns the number of local variables used by the function to get the desired result. Code #1: # Im
1 min read