[SOLVED] Local Variable Referenced Before Assignment

Python treats variables referenced only inside a function as global variables. Any variable assigned to a function’s body is assumed to be a local variable unless explicitly declared as global.

Why Does This Error Occur?
Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the concept of variable declarations. Hence it searches for the variable whenever used. When not found, it throws the error.
Before we hop into the solutions, let’s have a look at what is the global and local variables.
Local Variable Declarations vs. Global Variable Declarations

Local Variable Referenced Before Assignment Error with Explanation
Try these examples yourself using our Online Compiler.
Let’s look at the following function:

Explanation
The variable myVar has been assigned a value twice. Once before the declaration of myFunction and within myFunction itself.
Using Global Variables
Passing the variable as global allows the function to recognize the variable outside the function.
Create Functions that Take in Parameters
Instead of initializing myVar as a global or local variable, it can be passed to the function as a parameter. This removes the need to create a variable in memory.
UnboundLocalError: local variable ‘DISTRO_NAME’
This error may occur when trying to launch the Anaconda Navigator in Linux Systems.
Upon launching Anaconda Navigator, the opening screen freezes and doesn’t proceed to load.
Try and update your Anaconda Navigator with the following command.
If solution one doesn’t work, you have to edit a file located at
After finding and opening the Python file, make the following changes:
In the function on line 159, simply add the line:
DISTRO_NAME = None
Save the file and re-launch Anaconda Navigator.
DJANGO – Local Variable Referenced Before Assignment [Form]
The program takes information from a form filled out by a user. Accordingly, an email is sent using the information.
Upon running you get the following error:
We have created a class myForm that creates instances of Django forms. It extracts the user’s name, email, and message to be sent.
A function GetContact is created to use the information from the Django form and produce an email. It takes one request parameter. Prior to sending the email, the function verifies the validity of the form. Upon True , .get() function is passed to fetch the name, email, and message. Finally, the email sent via the send_mail function
Why does the error occur?
We are initializing form under the if request.method == “POST” condition statement. Using the GET request, our variable form doesn’t get defined.
FAQs on Local Variable Referenced Before Assignment
With the help of the threading module, you can avoid using global variables in multi-threading. Make sure you lock and release your threads correctly to avoid the race condition.
Therefore, we have examined the local variable referenced before the assignment Exception in Python. The differences between a local and global variable declaration have been explained, and multiple solutions regarding the issue have been provided.
Trending Python Articles

How to Fix Local Variable Referenced Before Assignment Error in Python
Fixing local variable referenced before assignment error, create an rss reader in node, best visual studio code extensions for 2022, how to build a discord bot using typescript, how to deploy a php app using docker, how to deploy a deno app using docker, how to deploy a node app using docker, using puppeteer and jest for end-to-end testing, getting started with handlebars.js, build a real-time chat app with node, express, and socket.io, getting user location using javascript's geolocation api, getting started with moment.js, learn how to build a slack bot using node.js.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
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.
Local Variable referenced before assignment
I was wondering if you guys could help. I'm trying to do a simple view where it sends the user to the client creation form, but I keep getting this error:
local variable 'form' referenced before assignment
Looking at my code, I can't see whats wrong.
Anyone tell me where I went wrong?
- django-models
- django-views

- Please include the full traceback, it will well you what line the problem is happening on. – Ross Patterson Aug 29, 2011 at 19:31
- is the indentation correct in your code sample? – steabert Aug 29, 2011 at 19:33
2 Answers 2
This is what is happening:
- The if block is not being entered.
- The form variable is not defined.
- You then attempt to refer to the form variable in the return statement.
As to how to fix it, that's really for you to decide. What the fix is depends on what you want your code to do in case the request method is not POST .

- What do you want to return when the request method is not POST ? – David Heffernan Aug 29, 2011 at 19:33
- What I am trying to do is produce a form, in which the user can enter the information and submit.. if the user doesnt fulfill the needs of the form, then do not submit the form – TheLifeOfSteve Aug 29, 2011 at 19:37
- I don't know what code you need to write to handle the case when request.method != 'POST' . Only you know that. For example do you want to do return render_to_response(...) ? – David Heffernan Aug 29, 2011 at 19:40
You almost certainly want to de-indent this part:
That is, on the initial GET of the page, use a blank client form, then when the page is POSTed, use the request POST data to fill in the form object.
- Thanks, this helped in some code I had which was giving me the same message in PyCharm – MichaelF May 15, 2014 at 12:40
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged python django django-models django-views or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- "Is" or "are" for two uncountable words?
- Is this summary of MCMC correct?
- Non-trivial semisubgroups of the unit interval?
- Serialization and deserialization doubly-linked list with pointer to random node on c++
- What is the difference between paper presentation and poster presentation?
- Is there a non-constant function on the sphere that diagonalizes all rotations simultaneously?
- Should sticker on top of HDD be peeled?
- Choice of Basis for solution space of a Hamiltonian
- Earn CC flight miles by paying rent?
- Why do academics stay as adjuncts for years rather than move around?
- What video game is Charlie playing in Poker Face S01E07?
- Displaying label if field contains 'X' or 'Y' value in QGIS
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- Rolling cube on an infinite chessboard
- Will DL360 Gen 8 servers fit in rails designed for DL360 Gen 7 servers?
- Is there a single-word adjective for "having exceptionally strong moral principles"?
- Can carbocations exist in a nonpolar solvent?
- What are the Stargate dial home device symbols used to dial Earth from Atlantis?
- Why does it seem like I am losing IP addresses after subnetting with the subnet mask of 255.255.255.192/26?
- Wavefunction of a particle decay
- My code is GPL licensed, can I issue a license to have my code be distributed in a specific MIT licensed project?
- Multiple tables with red color curly brackets
- How to sample a complex function?
- Active thermistor giving skewed readings immediately when heating element turned on
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Ohio Digital
- Onnet Consoulting
- AHT Training Center
By Industry
- Distribution
- Manufacturing
- Hi- Tech startup
Our realized projects

MB Securities


Local variable referenced before assignment: The UnboundLocalError in Python
When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. Because you try to use a local variable referenced before assignment. So, in this guide, we talk about what this error means and why it is raised. We walk through an example in action to help you understand how you can solve it.
Source: careerkarma

What is UnboundLocalError: local variable referenced before assignment?
Trying to assign a value to a variable that does not have local scope can result in this error:
Python has a simple rule to determine the scope of a variable. To clarify, a variable is assigned in a function, that variable is local. Because it is assumed that when you define a variable inside a function, you only need to access it inside that function.
There are two variable scopes in Python: local and global. Global variables are accessible throughout an entire program. Whereas, local variables are only accessible within the function in which they are originally defined.
An example of Local variable referenced before assignment
We’re going to write a program that calculates the grade a student has earned in class.
Firstly, we start by declaring two variables:
These variables store the numerical and letter grades a student has earned, respectively. By default, the value of “letter” is “F”. Then, we write a function that calculates a student’s letter grade based on their numerical grade using an “if” statement:
Finally, we call our function:
This line of code prints out the value returned by the calculate_grade() function to the console. We pass through one parameter into our function: numerical. This is the numerical value of the grade a student has earned.
Let’s run our code of Local variable referenced before assignment and see what happens:
Here is an error!
The Solution of Local variable referenced before assignment
The code returns an error: Unboundlocalerror local variable referenced before assignment because we reference “letter” before we assign it.
We have set the value of “numerical” to 42. Our if statement does not set a value for any grade over 50. This means that when we call our calculate_grade() function, our return statement does not know the value to which we are referring.
Moreover, we do define “letter” at the start of our program. However, we define it in the global context. Because Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.
Therefore, this problem of variable referenced before assignment could be solved in two ways. Firstly, we can add an else statement to our code. This ensures we declare “letter” before we try to return it:
Let’s try to run our code again:
Our code successfully prints out the student’s grade. This approach is good because it lets us keep “letter” in the local context. To clarify, we could even remove the “letter = “F”” statement from the top of our code because we do not use it in the global context.
Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our calculate_grade() function:
We use the “global” keyword at the start of our function.
This keyword changes the scope of our variable to a global variable. This means the “return” statement will no longer treat “letter” like a local variable. Let’s run our code. Our code returns: F.
The code works successfully! Let’s try it using a different grade number by setting the value of “numerical” to a new number:
Our code returns: B.
Finally, we have fixed the local variable referenced before assignment error in the code.
To sum up, as you can see, the UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. Then, you can solve this error by ensuring that a local variable is declared before you assign it a value. Moreover, if a variable is declared globally that you want to access in a function, you can use the “global” keyword to change its value. In case you have any inquiry, let’s CONTACT US . With a lot of experience in Mobile app development services , we will surely solve it for you instantly.
>>> Read more
- Average python length: How to find it with examples
- List assignment index out of range: Python indexerror solution you should know
- Spyder vs Pycharm: The detailed comparison to get best option for Python programming
- arrowhitech python , fix python error , Local variable referenced before assignment , python , python dictionary , python error , python learning , UnboundLocalError , UnboundLocalError in Python
Our Other Services
- E-commerce Development
- Web Apps Development
- Web CMS Development
- Mobile Apps Development
- Software Consultant & Development
- System Integration & Data Migration
- Dedicated Developers & Testers For Hire
- Remote Working Team
- Offshore Development Center
- Saas Products Development
- Web/Mobile App Development
- Outsourcing
- Hiring Developers
- Digital Transformation
- Advanced SEO Tips

Lastest News

Discovery Commerce Trends in the Telecommunications Industry for 2023

IaaS vs PaaS vs SaaS: Differences what you need to know

Saas Development Outsourcing: Reasons why you should choose Saas Development Outsourcing

Top awesome Python website examples

The complete guide to build a Python web application with amazing examples

Why ReactJS framework is the ideal solution for the SaaS product development
Tailor your experience
- Success Stories
Copyright ©2007 – 2021 by AHT TECH JSC. All Rights Reserved.

- No suggested jump to results
- Notifications
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 'request' referenced before assignment #492
CasellaJr commented Aug 26, 2022
- 👍 1 reaction
- 👀 1 reaction
igor-davidyuk commented Aug 29, 2022
Sorry, something went wrong.
CasellaJr commented Aug 29, 2022
Igor-davidyuk commented aug 30, 2022 • edited.
- 👍 2 reactions
CasellaJr commented Aug 30, 2022
CasellaJr commented Dec 8, 2022
Igor-davidyuk commented dec 8, 2022, igor-davidyuk commented dec 11, 2022.
No branches or pull requests
Local variable referenced before assignment in Python
In Python, while working with functions, you can encounter various types of errors. A common error when working with the functions is “ Local variable referenced before assignment ”. The stated error occurs when a local variable is referenced before being assigned any value.
This write-up will provide the possible reasons and the appropriate solutions to the error “Local variable referenced before assignment” with practical examples. The following aspects are discussed in this write-up in detail:
Reason: Reference a Local Variable
Solution 1: mark the variable globally, solution 2: using function parameter value, solution 3: using nonlocal keyword.
The main reason for the “ local variable referenced before assignment ” error in Python is using a variable that does not have local scope. This also means referencing a local variable without assigning it a value in a function.
The variable initialized inside the function will only be accessed inside the function, and these variables are known as local variables. To use variables in the entire program, variables must be initialized globally. The below example illustrates how the “ UnboundLocalError ” occurs in Python.

In the above snippet, the “ Student ” variable is not marked as global, so when it is accessed inside the function, the Python interpreter returns an error.
Note: We can access the outer variable inside the function, but when the new value is assigned to a variable, the “UnboundLocalError” appears on the screen.
To solve this error, we must mark the “ Student ” variable as a global variable using the keyword “ global ” inside the function.
In the above code, the local variable is marked as a “ global ” variable inside the function. We can easily reference the variable before assigning the variable in the program.

The above snippet proves that the global keyword resolves the “unboundLocalError”.
Passing a value as an argument to the function will also resolve the stated error. The function accepts the variable as an argument and uses the argument value inside the function. Let’s have a look at the given below code block for a better understanding:
In the above code, the variable is referenced before assigning the value inside the user-defined function. The program executes successfully without any errors because the variable is passed as a parameter value of the function.

The above output shows the value of the function when the function is accessed in the program without any “ Local Variable referenced ” error.
The “ nonlocal ” keyword is utilized in the program to assign a new value to a local variable of function in the nested function. Here is an example of code:
In the above code, the keyword “ nonlocal ” is used to mark the local variable of the outer function as nonlocal. After making the variable nonlocal, we can reference it before assigning a value without any error.

The above output shows the value of the inner function without any “ local variable referenced ” error in a program.
The “ Local variable referenced before assignment ” appears in Python due to assigning a value to a variable that does not have a local scope. To fix this error, the global keyword, return statement, and nonlocal nested function is used in Python script. The global keywords are used with variables to make it able to access inside and outside the function. The return statement is also used to return the variable’s new value back to function and display the result on the screen. This Python guide presented a detailed overview of the reason and solutions for the error “Local variable referenced before assignment” in Python.


IMAGES
VIDEO
COMMENTS
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.
UnboundLocalError: local variable 'total' referenced before assignment. At the start of the file (before the function where the error comes from), I declare total using the global keyword. Then, in the body of the program, before the function that uses total is called, I assign it to 0.
Local Variables can only be accessed within their own function. All functions of the program can access global variables. Local variables are immune to changes in the global scope. Thereby being more secure. Global Variables are less safer from manipulation as they are accessible in the global scope.
Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function, that variable is local. This is because it is assumed that when you define a variable inside a function you only need to access it inside that function. There are two variable scopes in Python: local and global.
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 …
Local Variable referenced before assignment. I was wondering if you guys could help. I'm trying to do a simple view where it sends the user to the client creation form, but I keep getting this error: Looking at my code, I can't see whats wrong. def add_client (request): user = request.user if request.method =='POST': form = AddClientForm ...
To sum up, as you can see, the UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. Then, you can solve this error by ensuring that a local variable is declared before you assign it a value.
For my experiments on CIFAR-10, until now I have used ResNet-18 or an EfficientNet. In the jupyter notebook, I initialise these models in this way: resnet18 = torchvision.models.resnet18(pretrained...
Solution 1: Mark the Variable globally Solution 2: Using Function Parameter Value Solution 3: Using nonlocal Keyword Reason: Reference a Local Variable The main reason for the “ local variable referenced before assignment ” error in Python is using a variable that does not have local scope.
The UnboundLocalError: local variable referenced before assignment occurs when you reference a local variable before assigning any value to it inside a function. The UnboundLocalError can be resolved by changing the variable's scope to global using the global keyword inside the function definition. How to Reproduce the Error