- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
Staging Ground badges
Earn badges by improving or asking questions in Staging Ground.
Python 3: UnboundLocalError: local variable referenced before assignment [duplicate]
The following code gives the error UnboundLocalError: local variable 'Var1' referenced before assignment :
How can I fix this?
- 2 Notice that it will work if you use dic = {'Var1':1, 'Var2':0} and access Var1 and Var2 through the dictionary. – xslittlegrass Commented Aug 10, 2017 at 5:07
- 11 Beside the point, but Var1 =- 1 is parsed as Var1 = -1 , not Var1 -= 1 – wjandrea Commented Mar 31, 2020 at 17:54
- How comes doesn't give error UnboundLocalError: local variable 'Var2' referenced before assignment? Even when you change if Var2 == 0 and Var1 > 0: to if Var2 == 0: – chikitin Commented Sep 11, 2020 at 17:34
- 3 @chikitin It doesn't give error for Var2 because in your function you have no where assigned any value to Var2, because of which it considers the global value of Var2 by default. But since, you have mentioned Var1=- 1 which python interprets as Var1 = -1, it considers that Var1 is assigned a local value and hence Var1 becomes a local & a global variable, which python considers separate. Since this assignment of Var1 comes after using Var1 in the same function, we get this reference before assignment error. Hope this gives some clarity – Sugandha Jain Commented Dec 14, 2020 at 16:13
- @chikitin Just in case, if you want to pop error for Var2 as well just to check and clarify your doubt, just assign some value to Var2 as well below Var1=-1 statement and then you'll get error for Var2 as well. – Sugandha Jain Commented Dec 14, 2020 at 16:16
5 Answers 5
This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function ( Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.
Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add, inside the top of your function :
This will tell Python that you do not intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.
Some Resources
- the Python website has a great explanation for this common issue.
- Python 3 offers a related nonlocal statement - check that out as well.
- 11 @user7344209 Indeed. Answers should ideally explain what's happening in the actual example shown, and how to fix that, rather than suggesting a whole different approach. – Stephen Holt Commented Sep 19, 2018 at 20:58
- 8 "Naturally", it does not seem natural to me. – dumbledad Commented Jan 3, 2020 at 10:04
- @dumbledad I only mean “naturally” in the sense that += is an assignment operator ( iadd , which stands for “in-place add”) – orokusaki Commented Jan 3, 2020 at 15:16
- 6 Nicely explained with a workable solution – Anant Tyagi Commented Feb 11, 2020 at 6:50
- What is the process that is to blame for this kind of phenomenon? I'd like to look into if other languages do something similar but I'm not sure what to google. – lightbox142 Commented Aug 15, 2020 at 19:36
If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.
In your case, Var1 is considered as a local variable, and it's used before being set, thus the error.
To solve this problem, you can explicitly say it's a global by putting global Var1 in you function.
You can fix this by passing parameters rather than relying on Globals
- 30 I think this simple sample code just shows the issue. The specific solution is not clear enough for such a case. – Karimai Commented Feb 10, 2019 at 20:41
- The last line should be Var1 -= 1 instead of Var1 - 1 – Leon Chang Commented Apr 27, 2022 at 1:56
I don't like this behavior, but this is how Python works. The question has already been answered by others, but for completeness, let me point out that Python 2 has more such quirks.
Python 2.7.6 returns an error:
Python sees the f is used as a local variable in [f for f in [1, 2, 3]] , and decides that it is also a local variable in f(3) . You could add a global f statement:
It does work; however, f becomes 3 at the end... That is, print [f for f in [1, 2, 3]] now changes the global variable f to 3 , so it is not a function any more.
Fortunately, it works fine in Python3 after adding the parentheses to print .
Why not simply return your calculated value and let the caller modify the global variable. It's not a good idea to manipulate a global variable within a function, as below:
or even make local copies of the global variables and work with them and return the results which the caller can then assign appropriately
Not the answer you're looking for? Browse other questions tagged python python-3.x scope or ask your own question .
- The Overflow Blog
- Is this the real life? Training autonomous cars with simulations
- Featured on Meta
- Preventing unauthorized automated access to the network
- Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
- Feedback Requested: How do you use the tagged questions page?
- Proposed designs to update the homepage for logged-in users
Hot Network Questions
- How would an ancient Chinese necromancer delay their zombies from rotting?
- Is this ring isomorphic to a quotient of a group algebra?
- How can I seal the joint between my wall tile and bathroom countertop?
- TV show that was on Netflix with a Viking boy who is in the modern world and a friend who is a ginger school kid
- How to typeset such table?
- Shading problem with Game Asset
- Rationale for requiring struct prefix in C
- How should I handle students who are very disengaged in class?
- Will I have enough time to connect between Paris Gare du Nord and Gare de l’Est accounting for any passport control?
- What type of firearm is ideal in zero gravity infantry asteroid combat?
- How to check dies temperatures on a modern RISC mac?
- Is there a security vulnerability in Advanced Custom Fields related to the SCF fork?
- How to use TL431 as a comparator to switch NPN transistor?
- Can 'be fruitful'(Genesis 1:28) be expressed as an invitation rather than an obligation?
- Infinite series involving product of four gamma functions
- SSH client does not offer public key to SSH server
- I've been hunting for a new job. Should I adjust my job title for each application?
- Why the title The Silver Chair?
- How to prevent partition-only differences in QAT output?
- Why does \zcref{...} give the wrong type of a reference?
- Filling gaps in weatherproof switch gland
- What does BS EN 1150 certification of cycling jackets actually require re flouresence and sizing?
- Does painting or staining a fence make it last longer?
- Offering shelter to homeless employees
How to Fix Local Variable Referenced Before Assignment Error in Python
Table of Contents
Fixing local variable referenced before assignment error.
In Python , when you try to reference a variable that hasn't yet been given a value (assigned), it will throw an error.
That error will look like this:
In this post, we'll see examples of what causes this and how to fix it.
Let's begin by looking at an example of this error:
If you run this code, you'll get
The issue is that in this line:
We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the variable that we defined in the first line.
If we want to refer the variable that was defined in the first line, we can make use of the global keyword.
The global keyword is used to refer to a variable that is defined outside of a function.
Let's look at how using global can fix our issue here:
Global variables have global scope, so you can referenced them anywhere in your code, thus avoiding the error.
If you run this code, you'll get this output:
In this post, we learned at how to avoid the local variable referenced before assignment error in Python.
The error stems from trying to refer to a variable without an assigned value, so either make use of a global variable using the global keyword, or assign the variable a value before using it.
Thanks for reading!
- Privacy Policy
- Terms of Service
How to fix UnboundLocalError: local variable 'x' referenced before assignment in Python
You could also see this error when you forget to pass the variable as an argument to your function.
How to reproduce this error
How to fix this error.
I hope this tutorial is useful. See you in other tutorials.
IMAGES
VIDEO