[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.
Local variable Referenced before assignment but it is global
This is a common error that happens when we don’t provide a value to a variable and reference it. This can happen with local variables. Global variables can’t be assigned.
This error message is raised when a variable is referenced before it has been assigned a value within the local scope of a function, even though it is a global variable.
Here’s an example to help illustrate the problem:
In this example, x is a global variable that is defined outside of the function my_func(). However, when we try to print the value of x inside the function, we get a UnboundLocalError with the message “local variable ‘x’ referenced before assignment”.
This is because the += operator implicitly creates a local variable within the function’s scope, which shadows the global variable of the same name. Since we’re trying to access the value of x before it’s been assigned a value within the local scope, the interpreter raises an error.
To fix this, you can use the global keyword to explicitly refer to the global variable within the function’s scope:
However, in the above example, the global keyword tells Python that we want to modify the value of the global variable x, rather than creating a new local variable. This allows us to access and modify the global variable within the function’s scope, without causing any errors.
Local variable ‘version’ referenced before assignment ubuntu-drivers
This error occurs with Ubuntu version drivers. To solve this error, you can re-specify the version information and give a split as 2 –
Here, p_name means package name.
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.
When a variable that is created locally is called before assigning, it results in Unbound Local Error in Python. The interpreter can’t track the variable.
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

Explore your training options in 10 minutes Get Started
- Graduate Stories
- Partner Spotlights
- Bootcamp Prep
- Bootcamp Admissions
- University Bootcamps
- Software Engineering
- Web Development
- Data Science
- Tech Guides
- Tech Resources
- Career Advice
- Online Learning
- Internships
- Apprenticeships
- Tech Salaries
- Associate Degree
- Bachelor's Degree
- Master's Degree
- University Admissions
- Best Schools
- Certifications
- Bootcamp Financing
- Higher Ed Financing
- Scholarships
- Financial Aid
- Best Coding Bootcamps
- Best Online Bootcamps
- Best Web Design Bootcamps
- Best Data Science Bootcamps
- Best Technology Sales Bootcamps
- Best Data Analytics Bootcamps
- Best Cybersecurity Bootcamps
- Best Digital Marketing Bootcamps
- Los Angeles
- San Francisco
- Browse All Locations
- Digital Marketing
- Machine Learning
- See All Subjects
- Bootcamps 101
- Full-Stack Development
- Career Changes
- View all Career Discussions
- Mobile App Development
- Cybersecurity
- Product Management
- UX/UI Design
- What is a Coding Bootcamp?
- Are Coding Bootcamps Worth It?
- How to Choose a Coding Bootcamp
- Best Online Coding Bootcamps and Courses
- Best Free Bootcamps and Coding Training
- Coding Bootcamp vs. Community College
- Coding Bootcamp vs. Self-Learning
- Bootcamps vs. Certifications: Compared
- What Is a Coding Bootcamp Job Guarantee?
- How to Pay for Coding Bootcamp
- Ultimate Guide to Coding Bootcamp Loans
- Best Coding Bootcamp Scholarships and Grants
- Education Stipends for Coding Bootcamps
- Get Your Coding Bootcamp Sponsored by Your Employer
- GI Bill and Coding Bootcamps
- Tech Intevriews
- Our Enterprise Solution
- Connect With Us
- Publication
- Reskill America
- Partner With Us

- Resource Center
- Coding Tools
- Bachelor’s Degree
- Master’s Degree
Python local variable referenced before assignment Solution
When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. This error is raised when you try to use a variable before it has been assigned in the local context .
In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you understand how you can solve it.
Find your bootcamp match
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. 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. Global variables are accessible throughout an entire program; local variables are only accessible within the function in which they are originally defined.
Let’s take a look at how to solve this error.
An Example Scenario
We’re going to write a program that calculates the grade a student has earned in class.
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”. Next, 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 and see what happens:
An error has been raised.

The Solution
Our code returns an error 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.
We do define “letter” at the start of our program. However, we define it in the global context. Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.
We solve this problem in two ways. First, 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.
If you are using an “if” statement where you declare a variable, you should make sure there is an “else” statement in place. This will make sure that even if none of your if statements evaluate to True, you can still set a value for the variable with which you are going to work.
Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our calculate_grade() function. However, this approach is likely to lead to more confusing code and other issues. In general, variables should not be declared using “global” unless absolutely necessary . Your first, and main, port of call should always be to make sure that a variable is correctly defined.
In the example above, for instance, we did not check that the variable “letter” was defined in all use cases.
That’s it! We have fixed the local variable error in our code.
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. You can solve this error by ensuring that a local variable is declared before you assign it a value.
Now you’re ready to solve UnboundLocalError Python errors like a professional developer !
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .
What's Next?

Get matched with top bootcamps
Ask a question to our community, take our careers quiz.

UnboundLocalError: local variable referenced before assignment
The "UnboundLocalError: local variable referenced before assignment" in Python occurs when you try to access a local variable before it has been assigned a value within the current scope or function. Python requires that you initialize a variable before using it in the same scope to avoid ambiguity and undefined behavior.
To resolve this error, you can follow these steps:
- Initialize the variable: Ensure that you assign a value to the variable before referencing it within the same scope.
- Check the variable scope: Verify that you are not trying to access the variable from outside its defined scope.
- Use global keyword : If you want to access a global variable from within a function, use the global keyword to indicate that the variable is defined in the global scope.
Variable not assigned before use
In this example, the variable "x" is referenced before it is assigned any value within the function. Python raises the UnboundLocalError since the variable is accessed before being defined.
To fix this, assign a value to the variable before referencing it:
Accessing global variable without 'global' keyword
In this example, the function tries to modify the global variable "x" without using the global keyword. This results in the UnboundLocalError.
To resolve this, use the global keyword to indicate that the variable is in the global scope:
In Python, lexical scoping is the default behavior, where inner scopes can access values from enclosing scopes, but they cannot modify those values unless explicitly declared global using the "global" keyword. When variables are assigned values within a function, they are stored in the local symbol table. However, when referencing variables, Python first looks in the local symbol table, then in the global symbol table, and finally in the built-in names table. This design leads to a restriction where global variables cannot be directly assigned new values within a function, unless they are explicitly named in a global statement. Nevertheless, global variables can be referenced within functions. By adhering to these lexical scoping principles and utilizing the "global" keyword when necessary, Python developers can ensure proper variable behavior and maintain the integrity of variable assignments across different scopes, promoting code reliability and clarity.
By following these best practices and ensuring variable assignment before referencing within the same scope, you can overcome the UnboundLocalError and ensure the proper functioning of your Python code.
- TypeError: 'NoneType' object is not subscriptable
- IndexError: string index out of range
- IndentationError: unexpected indent Error
- ValueError: too many values to unpack (expected 2)
- SyntaxError- EOL while scanning string literal
- TypeError: Can't convert 'int' object to str implicitly
- IndentationError: expected an indented block
- ValueError: invalid literal for int() with base 10
- IndexError: list index out of range : Python
- AttributeError: 'module' object has no attribute 'main'
- TypeError: string indices must be integers
- FileNotFoundError: [Errno 2] No such file or directory
- Fatal error: Python.h: No such file or directory
- ZeroDivisionError: division by zero
- ImportError: No module named requests | Python
- TypeError: 'NoneType' object is not iterable
- SyntaxError: unexpected EOF while parsing | Python
- zsh: command not found: python
- Unicodeescape codec can't decode bytes in position 2-3
- The TypeError: 'tuple' object does not support item assignment
- The AttributeError: 'bytes' object has no attribute 'read'
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.
Within the function, we can assign a new value to the student variable without any error. Let’s have a look at the below snippet for a detailed understanding:
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.

Local variable 'bkey_hash' referenced before assignment
Each step is a challenge, now to populate my table I’m getting the return below:
Traceback (most recent call last): File “c:\Users\EliasPai\kivy_venv\lib\site-packages\flask\app.py”, line 2525, in wsgi_app response = self.full_dispatch_request() File “c:\Users\EliasPai\kivy_venv\lib\site-packages\flask\app.py”, line 1822, in full_dispatch_request rv = self.handle_user_exception(e) File “c:\Users\EliasPai\kivy_venv\lib\site-packages\flask\app.py”, line 1820, in full_dispatch_request rv = self.dispatch_request() File “c:\Users\EliasPai\kivy_venv\lib\site-packages\flask\app.py”, line 1796, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) File “c:\Users\EliasPai\kivy_venv\lib\site-packages\dash\dash.py”, line 1259, in dispatch ctx.run( File “c:\Users\EliasPai\kivy_venv\lib\site-packages\dash_callback.py”, line 439, in add_context output_value = func(*func_args, **func_kwargs) # %% callback invoked %% File “c:\Users\EliasPai\kivy_venv\lib\site-packages\dash_extensions\callback.py”, line 171, in decorated_function args[i] = self.cache.get(args[i]) File “c:\Users\EliasPai\kivy_venv\lib\site-packages\cachelib\file.py”, line 205, in get filename = self._get_filename(key) File “c:\Users\EliasPai\kivy_venv\lib\site-packages\cachelib\file.py”, line 202, in _get_filename return os.path.join(self._path, bkey_hash) UnboundLocalError: local variable ‘bkey_hash’ referenced before assignment
Just below is my callback:
I found the cause but not the solution yet. The cause is because there are two Outputs, it seems that it is only accepting one return. That is, when it is conjugated it presents the error.
What version are you on?
In any case, please try updating to latest version of Dash and dash-extensions, and clear any local cache (e.g. on the filesystem).
It didn’t. This is the list of applications involved:
Python==3.10.7 cachelib==0.9.0 dash==2.6.1 dash-bootstrap-components==1.2.1 dash-bootstrap-templates==1.0.7 dash-core-components==2.0.0 dash-extensions==0.0.23 dash-html-components==2.0.0 dash-table==5.0.0 Deprecated==1.2.13 distro==1.7.0 dnspython==2.2.1 docutils==0.19 Flask==2.2.2 Flask-Caching==2.0.1 Flask-Compress==1.12 numpy==1.23.2 oauth2client==4.1.3 openpyxl==3.0.10 pandas==1.4.4 plotly==5.10.0 protobuf==4.21.5 redis==4.3.4 toml==0.10.2
Your dash-extensions version is very old. The latest version is 0.1.7, please try upgrading to that one.
Now it is showing import errors:
File “c:\Users\EliasPai\DocumentsRIKA\DashRika\app.py”, line 29, in from dash_extensions.callback import CallbackCache, Trigger ModuleNotFoundError: No module named ‘dash_extensions.callback’
In the documentation I didn’t find this term.
I am basing this example on the link.
That link is to a very old post. Please refer to recent documentation,
Thank you very much for your help my brother!
UnboundLocalError: local variable 'newpath' referenced before assignment
Hello! I need help . every time I plot my data, the error message below appears. This bug appeared a few days ago.
can you paste the path of the file you’re trying to plot?
import numpy as np import matplotlib.pyplot as plt import pathlib import mne import os
raw = mne.io.read_raw_nihon(‘DA96301A.EEG’) raw.plot()
Could you share the output of:
And the output of:
And could you check if:
raises the same error or not?
Yes! Raises the same error !
import mne mne.sys_info()
Platform: Windows-10-10.0.19041-SP0 Python: 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] Executable: C:\ProgramData\Anaconda3\python.exe CPU: Intel64 Family 6 Model 158 Stepping 10, GenuineIntel: 12 cores Memory: 63.9 GB
mne: 1.0.dev0 numpy: 1.18.1 {blas=mkl_rt, lapack=mkl_rt} scipy: 1.4.1 matplotlib: 3.1.3 {backend=module://ipykernel.pylab.backend_inline}
sklearn: 0.23.2 numba: 0.48.0 nibabel: 3.2.1 nilearn: 0.8.0 dipy: 1.3.0 cupy: Not found pandas: 1.0.1 pyvista: Not found pyvistaqt: Not found ipyvtklink: Not found vtk: Not found PyQt5: 5.9.2 ipympl: Not found pooch: v1.6.0
mne_bids: Not found mne_nirs: Not found mne_features: Not found mne_qt_browser: Not found mne_connectivity: Not found
Well… now I am a bit surprised. This code snippet does not raise for me, neither with mne 0.24.1 nor with the latest 1.0.dev0 version.
I would suggest trying to create a fresh environment and install MNE in it via the default channels. See if it still raises in a fresh env.
An UnboundLocalError is raised when a local variable is referenced before it has been assigned. In most cases this will occur when trying to modify a local variable before it is actually assigned within the local scope. Python doesn’t have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.
Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they’re declared global with the global keyword). A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can’t modify the binding in the enclosing environment. UnboundLocalError happend because when python sees an assignment inside a function then it considers that variable as local variable and will not fetch its value from enclosing or global scope when we execute the function. However, to modify a global variable inside a function, you must use the global keyword.
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
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 'masters' referenced before assignment #497
pebel76260 commented Mar 10, 2021 • edited
danielhrisca commented Mar 17, 2021
Sorry, something went wrong.
No branches or pull requests

IMAGES
VIDEO
COMMENTS
Qualitative variables are those with no natural or logical order. While scientists often assign a number to each, these numbers are not meaningful in any way. Examples of qualitative variables include things such as color, shape or pattern.
When Europeans first began assigning each other surnames to differentiate individuals in expanding urban areas, the names frequently referenced someone’s appearance or the place that they were from. Names such as “Long,” “Short,” “Black” an...
In experimental research, researchers use controllable variables to see if manipulation of these variables has an effect on the experiment’s outcome. Additionally, subjects of the experimental research are randomly assigned to prevent bias ...
Anyway, you don't really need to worry about importing numpy. Just do import numpy as np unconditionally. If it's already imported, it will just
Why Does This Error Occur? ... Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created.
The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it
Что делать с ошибкой UnboundLocalError: local variable referenced before assignment. Главное — определиться с областью видимости и решить
The "UnboundLocalError: local variable referenced before assignment" in Python occurs when you try to access a local variable before it has been assigned a
How to solve this Python exception: local variable 'article' referenced before assignment, Why am I getting this error "local variable
In Python, the Local variable referenced before assignment occurs when you assign a value to a variable that does not have a local scope.
Friends, Each step is a challenge, now to populate my table I'm getting the return below: Traceback (most recent call last): File
... python 3.6.5) Got error "UnboundLocalError: local variable 'name' referenced before assignment" when import jax.numpy as np /anaconda3...
An UnboundLocalError is raised when a local variable is referenced before it has been assigned. In most cases this will occur when trying to
np.searchsorted(masters[group_index], start).flatten()[0] - 1, 0 UnboundLocalError: local variable 'masters' referenced before assignment