UnboundLocalError Local variable Referenced Before Assignment in Python
Last Updated :
01 Mar, 2024
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, we will delve into the intricacies of the UnboundLocalError and provide a comprehensive guide on how to effectively use try-except statements to resolve it.
What is UnboundLocalError Local variable Referenced Before Assignment in Python?
The UnboundLocalError 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 'result' referenced before assignment
Why does UnboundLocalError: Local variable Referenced Before Assignment Occur?
below, are the reasons of occurring "Unboundlocalerror: Try Except Statements" in Python:
- Variable Assignment Inside Try Block
- Reassigning a Global Variable Inside Except Block
- Accessing a Variable Defined Inside an If Block
Variable Assignment Inside Try Block
In the below code, example_function
attempts to execute some_operation
within a try-except block. If an exception occurs, it prints an error message. However, if no exception occurs, it prints the value of the variable result
outside the try block, leading to an UnboundLocalError since result
might not be defined if an exception was caught.
Python3
def example_function():
try:
result = some_operation()
except Exception as e:
print("An error occurred:", e)
print(result)
# Calling the function
example_function()
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 9, in <module>
example_function()
File "Solution.py", line 6, in example_function
print(result)
UnboundLocalError: local variable 'result' referenced before assignment
Reassigning a Global Variable Inside Except Block
In below code , modify_global
function attempts to increment the global variable global_var
within a try block, but it raises an UnboundLocalError. This error occurs because the function treats global_var
as a local variable due to the assignment operation within the try block.
Python3
global_var = 42
def modify_global():
try:
global_var += 1
except Exception as e:
print("An error occurred:", e)
print(global_var)
# Calling the function
modify_global()
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 11, in <module>
modify_global()
File "Solution.py", line 8, in modify_global
print(global_var)
UnboundLocalError: local variable 'global_var' referenced before assignment
Solution for UnboundLocalError Local variable Referenced Before Assignment
Below, are the approaches to solve "Unboundlocalerror: Try Except Statements".
- Initialize Variables Outside the Try Block
- Avoid Reassignment of Global Variables
Initialize Variables Outside the Try Block
In modification to the example_function
is correct. Initializing the variable result
before the try block ensures that it exists even if an exception occurs within the try block. This helps prevent UnboundLocalError when trying to access result
in the print statement outside the try block.
Python3
def example_function():
result = None # Initialize the variable before the try block
try:
result = some_operation()
except Exception as e:
print("An error occurred:", e)
print(result)
Avoid Reassignment of Global Variables
Below, code calculates a new value (local_var
) based on the global variable and then prints both the local and global variables separately. It demonstrates that the global variable is accessed directly without being reassigned within the function.
Python3
global_var = 42
def modify_global():
try:
local_var = global_var + 1
except Exception as e:
print("An error occurred:", e)
print(global_var) # Access the global variable directly
Conclusion
In conclusion , To fix "UnboundLocalError" related to try-except statements, ensure that variables used within the try block are initialized before the try block starts. This can be achieved by declaring the variables with default values or assigning them None outside the try block. Additionally, when modifying global variables within a try block, use the `global` keyword to explicitly declare them.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read