How to fix UnboundLocalError: local variable 'x' referenced before assignment in Python
by Nathan Sebhastian
Posted on May 26, 2023
Reading time: 2 minutes
One error you might encounter when running Python code is:
This error commonly occurs when you reference a variable inside a function without first assigning it a value.
You could also see this error when you forget to pass the variable as an argument to your function.
Let me show you an example that causes this error and how I fix it in practice.
How to reproduce this error
Suppose you have a variable called name declared in your Python code as follows:
Next, you created a function that uses the name variable as shown below:
When you execute the code above, you’ll get this error:
This error occurs because you both assign and reference a variable called name inside the function.
Python thinks you’re trying to assign the local variable name to name , which is not the case here because the original name variable we declared is a global variable.
How to fix this error
To resolve this error, you can change the variable’s name inside the function to something else. For example, name_with_title should work:
As an alternative, you can specify a name parameter in the greet() function to indicate that you require a variable to be passed to the function.
When calling the function, you need to pass a variable as follows:
This code allows Python to know that you intend to use the name variable which is passed as an argument to the function as part of the newly declared name variable.
Still, I would say that you need to use a different name when declaring a variable inside the function. Using the same name might confuse you in the future.
Here’s the best solution to the error:
Now it’s clear that we’re using the name variable given to the function as part of the value assigned to name_with_title . Way to go!
The UnboundLocalError: local variable 'x' referenced before assignment occurs when you reference a variable inside a function before declaring that variable.
To resolve this error, you need to use a different variable name when referencing the existing variable, or you can also specify a parameter for the function.
I hope this tutorial is useful. See you in other tutorials.
Take your skills to the next level ⚡️
I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.
Learn more about this website
Connect with me on Twitter
Or LinkedIn
Type the keyword below and hit enter
Click to see all tutorials tagged with:
- Python Basics
- Interview Questions
- Python Quiz
- Popular Packages
- Python Projects
- Practice Python
- AI With Python
- Learn Python3
- Python Automation
- Python Web Dev
- DSA with Python
- Python OOPs
- Dictionaries
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, 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.
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
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.
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.
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.
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.
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.
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 Programs
- Python Errors
Please Login to comment...
Improve your coding skills with practice.
What kind of Experience do you want to share?
Navigation Menu
Search code, repositories, users, issues, pull requests..., provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications You must be signed in to change notification settings
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
UnboundLocalError: local variable 'beta1' referenced before assignment #5083
CharlesChen24 commented Apr 29, 2021
shinya7y commented Apr 29, 2021
- 👍 7 reactions
Sorry, something went wrong.
fangxu622 commented May 21, 2021 • edited Loading
No branches or pull requests
COMMENTS
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 …
А ошибка local variable referenced before assignment означает, что переменная, которую вы вызываете не объявлена.
The UnboundLocalError: local variable 'x' referenced before assignment occurs when you reference a variable inside a function before declaring that variable. To resolve this error, you need to use a different …
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 …
When I run 'python tools/train.py configs/detr/detr_r50_8x2_150e_coco.py‘,An UnboundLocalError occured. Please help me. My env: GCC: gcc (GCC) 6.4.0 PyTorch: 1.8.0+cu111 …
UnboundLocalError: local variable 'l' referenced before assignment. вот сам код: import trimestr as tr. from datetime import date. now = date.today() x = date(2022, 12, 25) …
The error message states that the variable x has no value. Since it is assigned (repeatedly) in your for loop, this means that your for loop is not executing even once. And the only way this …