
Sometimes you may suddenly start getting UnboundLocalError in your code which was working perfectly just minutes ago. And what you did is just added an assignment statement.
Lets say your code is as below, which is working fine.
Now you added an assignment statement inside printx function where you are increasing the value of global variable x . You will start getting UnboundLocalError .
What caused UnboundLocalError?

Lets understand few things first.
In python all the variables inside a function are global if they are not assigned any value to them. That means if a variable is only referenced inside a function, it is global. However if we assign any value to a variable inside a function, its scope becomes local to that unless explicitly declared global.
In first example, we are not assigning any value to x variable inside function and just referencing it to print. Hence x is global.
In second example, we assigned the value 7 to x, hence x's scope is local to function and we tried to print it before assigning any value to x.
Similarly, you will get UnboundLocalError in scenario similar to below example.
UnboundLocalError can be solved by changing the scope of the variable which is complaining. You need to explicitly declare the variable global.
Variable x's scope in function printx is global. You can verify the same by printing the value of x in terminal and it will be 6.
Remember that same thing can be done using nonlocal keyword. But mind it that nonlocal binds the variable to nearest enclosing scope except global. Lets understand this with an example.
Output will be:
So take away is:
1. Use global keyword with a variable if only you are assigning value to that variable inside a function and you want to overwrite the value of variable declared in global scope.
2. Use nonlocal keyword in nested scopes.
Host your Django App for free (or in only $5 with custom domain name)

Hello, buddy!
I'm a coder. Welcome to my blog. Here are some of the records on my job.
Python (3.3): unboundlocalerror: local variable referenced before assignment.
SOLVED By Paul Rooney: At the top of xcode put global of
I have searched through other websites and throughout stacker overflow and cannot find a solution for this, this is a unique case of the mistake as I cannot state the variable within the definition. Whenever I start my game and let's say for example I enter 1,4 as the grid reference it will reply with
"UnboundLocalError: local variable 'of' referenced before assignment"
How can I fix this?
Variable of (and all the other 2-letter variables) are not available in function xturn .
I strongly recommend that you use incremental programming: write a few lines of code, get those working, and then enlarge your program. This allows you to zero in on errors quite easily. Any time I attack a new style of programming, I find this quite useful. It appears that you're new to some of the techniques you're using here.
For instance, you're using in instead of == for comparisons. This is not going to work well as a general principle.
Declare your functions before the main program. The way you wrote this, you're redefining your functions every time you go through the loop. Moving functions to the top will cure you of many variable scoping problems, too.
Learn to use Boolean values and variables. Your loops should look like this:
You make variables available by passing them as arguments to the function. I can see that you're new to this, because you've given this function a parameter x that you never use.
Overall, you should not have 9 variables: you should have a list, and then just pass the entire list as the current state of the game board. If you number the squares 0-8, you can easily work with the board in that respect.
To solve the immediate problem, you can add this line to each of your routines:
This will make the variables available. I see that @Thomas has pointed this out.
Still, I encourage you to work on designing this more cleanly. Using global variables is generally bad design. Also, notice how much code you have to duplicate for this program? It should be a lot easier.
Related Articles
Got unboundlocalerror: local variable referenced before assignment, but not, unboundlocalerror: local variable referenced before assignment using the csv file, get unboundlocalerror: local variable referenced before the assignment error, python 3: unboundlocalerror: local variable referenced before the assignment, unboundlocalerror: local variable referenced before the assignment (python), python error: local variable referenced before assignment, python & ldquo; local variable referenced before assignment & rdquo; with hundreds of threads, another unboundlocalerror: local variable referenced before the assignment, & ldquo; local variable referenced before assignment & rdquo; - only functions?, django context: local variable referenced before assignment, assignment to the parent function variable: & ldquo; local variable referenced before assignment & rdquo;, local variable referenced before assignment inside a class, local variable referenced before assignment for decorator, & ldquo; local variable referenced before assignment & rdquo; error when declaring the same variable as the imported class.
UnboundLocalError local variable 'context' referenced before assignment Django
I get the error below immediately after i add a new root url inside the root urls.py.
When i remove the dashboard view, url and i try to load index view, it renders successfully. What am i doing wrong or what can i do to resolve the issue.
Error message
blogapp urls.py
myblog urls.py the root file.
Below is an attachment of the django app files is set up.

The problem is that the variable context you created has the same name as the context you imported from multiprocessing at the top of the file. Changing the variable name should fix the problem.
You need to define context when if request.method == "GET"
Recent Questions & Answers
how can I use django model method for ordering in meta class
how to properly implement Django (Wagtail CMS) pagination in modal window using Select html tag?
I need to create documentation API for Django with MongoDB project?
Nginx Gives 502 Error but config should be correct; Please I need advise on how to debug the issue?
Как сократить двойной цикл For?
Django Admin inline-editable like Flask admin?
Django ValueError: Cannot serialize: <User: username>
Django - images upload in wrong folder
django rest framework + djoser ошибка при получении токена - "non_field_errors": [ "Невозможно войти с предоставленными учетными данными." ]
Django crispy forms language settings
Recommended entries on the topic
ThreadPoolExecutor in Python: The Complete Guide
Python Decorators
Python List Comprehensions
Pyton Regular Expressions
Modeling Trees with SQLAlchemy ORM and Postgres Ltree
Guide to Python Dictionaries
Guide to String Formatting with Python
A Guide to Python’s Flask Web Interface
Practical Machine Learning with Python and Keras
Best Practices for Using Functional Programming in Python
- Language: en
Python Language
- Getting started with Python Language
- Awesome Book
- Awesome Community
- Awesome Course
- Awesome Tutorial
- Awesome YouTube
- *args and **kwargs
- Abstract Base Classes (abc)
- Abstract syntax tree
- Accessing Python source code and bytecode
- Alternatives to switch statement from other languages
- Asyncio Module
- Attribute Access
- Basic Curses with Python
- Basic Input and Output
- Binary Data
- Bitwise Operators
- Boolean Operators
- Call Python from C#
- Checking Path Existence and Permissions
- ChemPy - python package
- CLI subcommands with precise help output
- Code blocks, execution frames, and namespaces
- Collections module
- Comments and Documentation
- Common Pitfalls
- Commonwealth Exceptions
- Comparisons
- Complex math
- Conditionals
- configparser
- Connecting Python to SQL Server
- Context Managers (“with” Statement)
- Copying data
- Create virtual environment with virtualenvwrapper in windows
- Creating a Windows service using Python
- Creating Python packages
- Data Serialization
- Data Visualization with Python
- Database Access
- Date and Time
- Date Formatting
- Defining functions with list arguments
- Deque Module
- Design Patterns
- Difference between Module and Package
- Distribution
- Dynamic code execution with `exec` and `eval`
- Exponentiation
- Files & Folders I/O
- Functional Programming in Python
- Functools Module
- Garbage Collection
- getting start with GZip
- Hidden Features
- HTML Parsing
- Immutable datatypes(int, float, str, tuple and frozensets)
- Importing modules
- Incompatibilities moving from Python 2 to Python 3
- Indentation
- Indexing and Slicing
- Input, Subset and Output External Data Files using Pandas
- Introduction to RabbitMQ using AMQPStorm
- IoT Programming with Python and Raspberry PI
- Iterables and Iterators
- Itertools Module
- JSON Module
- kivy - Cross-platform Python Framework for NUI Development
- Linked List Node
- Linked lists
- List comprehensions
- List Comprehensions
- List destructuring (aka packing and unpacking)
- List slicing (selecting parts of lists)
- Manipulating XML
- Map Function
- Math Module
- Metaclasses
- Method Overriding
- Multidimensional arrays
- Multiprocessing
- Multithreading
- Mutable vs Immutable (and Hashable) in Python
- Neo4j and Cypher using Py2Neo
- Non-official Python implementations
- Operator module
- Operator Precedence
- Optical Character Recognition
- Overloading
- Pandas Transform: Preform operations on groups and concatenate the results
- Parallel computation
- Parsing Command Line arguments
- Partial functions
- Performance optimization
- Pickle data serialisation
- pip: PyPI Package Manager
- Plotting with Matplotlib
- Plugin and Extension Classes
- Polymorphism
- Processes and Threads
- Property Objects
- pyautogui module
- PyInstaller - Distributing Python Code
- Python and Excel
- Python Anti-Patterns
- Python concurrency
- Python Data Types
- Python HTTP Server
- Python Lex-Yacc
- Python Networking
- Python Persistence
- Python Requests Post
- Python Serial Communication (pyserial)
- Python Server Sent Events
- Python speed of program
- Python Virtual Environment - virtualenv
- Queue Module
- Raise Custom Errors / Exceptions
- Random module
- Reading and Writing CSV
- Regular Expressions (Regex)
- Secure Shell Connection in Python
- Security and Cryptography
- Similarities in syntax, Differences in meaning: Python vs. JavaScript
- Simple Mathematical Operators
- Sockets And Message Encryption/Decryption Between Client and Server
- Sorting, Minimum and Maximum
- Sqlite3 Module
- String Formatting
- String Methods
- String representations of class instances: __str__ and __repr__ methods
- Subprocess Library
- tempfile NamedTemporaryFile
- Templates in python
- The __name__ special variable
- The base64 Module
- The dis module
- The Interpreter (Command Line Console)
- The locale Module
- The os Module
- The pass statement
- The Print Function
- Turtle Graphics
- Unicode and bytes
- Unit Testing
- Unzipping Files
- Usage of "pip" module: PyPI Package Manager
- User-Defined Methods
- Using loops within functions
- Variable Scope and Binding
- Binding Occurrence
- Functions skip class scope when looking up names
- Global Variables
- Local Variables
- Local vs Global Scope
- Nonlocal Variables
- The del command
- virtual environment with virtualenvwrapper
- Virtual environments
- Web scraping with Python
- Web Server Gateway Interface (WSGI)
- Webbrowser Module
- Working around the Global Interpreter Lock (GIL)
- Working with ZIP archives
- Writing extensions
- Writing to CSV from String or List

Python Language Variable Scope and Binding Global Variables
Fastest entity framework extensions.
In Python, variables inside functions are considered local if and only if they appear in the left side of an assignment statement, or some other binding occurrence; otherwise such a binding is looked up in enclosing functions, up to the global scope. This is true even if the assignment statement is never executed.
Normally, an assignment inside a scope will shadow any outer variables of the same name:
Declaring a name global means that, for the rest of the scope, any assignments to the name will happen at the module's top level:
The global keyword means that assignments will happen at the module's top level, not at the program's top level. Other modules will still need the usual dotted access to variables within the module.
To summarize: in order to know whether a variable x is local to a function, you should read the entire function:
- if you've found global x , then x is a global variable
- If you've found nonlocal x , then x belongs to an enclosing function, and is neither local nor global
- If you've found x = 5 or for x in range(3) or some other binding, then x is a local variable
- Otherwise x belongs to some enclosing scope (function scope, global scope, or builtins)
Got any Python Language Question?

- Advertise with us
- Privacy Policy
Get monthly updates about new articles, cheatsheets, and tricks.
[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 if statement [Fixed] SSL module in Python is Not Available](https://www.pythonpool.com/wp-content/uploads/2023/05/ssl-module-in-python-is-not-available-300x157.webp)
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

- 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.
"UnboundLocalError: local variable referenced before assignment" after an if statement [duplicate]
When I try this code:
I get an error that says
The first print works correctly but the second causes an exception. I tried making T a global variable but then both answers are the same.
What is going wrong, and how can I fix it?
- 1 to get rid of UnboundLocalError, the if statement has to run, so try give T a default value so that T is defined, refer to @shx2 answer – PurityLake Mar 12, 2013 at 17:20
- 1 Also, you are running an entire loop to get a single value. This way your loop will always return the last matching instance of data. You can make your code more efficient by reading it in reverse order and instead of assigning, return T – ferrix Mar 12, 2013 at 17:28
7 Answers 7
Your if statement is always false and T gets initialized only if a condition is met, so the code doesn't reach the point where T gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed.

FWIW: I got the same error for a different reason. I post the answer here not for the benefit of the OP, but for the benefit of those who may end up on this page due to its title... who might have made the same mistake I did.
I was confused why I was getting "local variable referenced before assignment" because I was calling a FUNCTION that I knew was already defined:
This was giving:
Took me a while to see my obvious problem: I used a local variable named job_fn which masked the ability to see the prior function definition for job_fn .
- 3 Another possible cause for the error. stackoverflow.com/questions/10506973/… – digao_mb May 10, 2016 at 11:23
- 1 There's actually an entry in the Python FAQ about this, and some other SO questions like this one – wjandrea Jun 13, 2020 at 3:15
The other answers are correct: You don't have a default value. However, you have another problem in your logic:
You read the same file twice. After reading it once, the cursor is at the end of the file, so trying to read it again returns nothing and the loop is never entered. To solve this, you can do two things: Either open/close the file upon each function call:
This has the disadvantage of having to open the file each time. The better way would be:
You do this after your for line in tfile: loop. It resets the cursor to the beginning so the next call will start from there again.
Related questions:
- Iterating on a file doesn't work the second time
- Why a file is empty after reading it?
- After my error was resolved I was still not getting the right answer and this was due to the file cursor not being in the right place. I have amended this as you suggested and is now working. Thanks – user1958508 Mar 12, 2013 at 18:32
Before I start, I'd like to note that I can't actually test this since your script reads data from a file that I don't have.
'T' is defined in a local scope for the declared function. In the first instance 'T' is assigned the value of 'data[2]' because the conditional statement above apparently evaluates to True. Since the second call to the function causes the 'UnboundLocalError' exception to occur, the local variable 'T' is getting set and the conditional assignment is never getting triggered.
Since you appear to want to return the first bit of data in the file that matches your conditonal statement, you might want to modify you function to look like this:
That way the desired value gets returned when it is found, and 'None' is returned when no matching data is found.
- 1 That is actually not identical behavior. The example given returns the last matching instance and you are returning the first instance. Reading the file from the end would work but a simple reversed() will not do if we don't want the entire file in memory. – ferrix Mar 12, 2013 at 17:31
I was facing same issue in my exercise. Although not related, yet might give some reference. I didn't get any error once I placed addition_result = 0 inside function. Hope it helps! Apologize if this answer is not in context.
Contributing to ferrix example,
My message will not execute, because none of my conditions are fulfill therefore receiving " UnboundLocalError: local variable 'range' referenced before assignment"
To Solve this Error just initialize that variable above that loop or statement. For Example var a =""
- This is Python, not JS – wjandrea Jun 9, 2020 at 20:30
Not the answer you're looking for? Browse other questions tagged python or ask your own question .
- The Overflow Blog
- CEO Update: Paving the road forward with AI and community at the center
- Building a safer community: Announcing our new Code of Conduct
- Featured on Meta
- AI/ML Tool examples part 3 - Title-Drafting Assistant
- We are graduating the updated button styling for vote arrows
- The [connect] tag is being burninated
- Temporary policy: ChatGPT is banned
- Does the policy change for AI-generated content affect users who (want to)...
Hot Network Questions
- Adjacent Items Sorting
- What's the difference between "последний" and "прошлый"?
- Removing phantom plugin from database
- Scope creep and creepy stories?
- Could a Nuclear-Thermal turbine keep a winged craft aloft on Titan at 5000m ASL?
- Why are American liberals more prone to in-fighting than conservatives?
- Can I increase the size of my floor register to improve cooling in my bedroom?
- Code readibility and debugging
- Word to describe someone who is ignorant of societal problems
- How i fetch comma separate email from system.xml
- Is there a definition/test for "lack of merit" (legal arguments)?
- Lines in qualitative linguistic transcription
- In the phrase "there's a good film on late", does "on" mean "on TV"?
- Citing "common knowledge" blogs?
- Verb for "ceasing to like someone/something"
- Solar-electric system not generating rated power
- How to mark seatpost position?
- Do you provoke an AoO when you evoke a beam with the spell Sunbeam?
- Could a steam-age civilization trial-and-error their way to a nuclear reactor if they had access to enough fissile material?
- Can this be a better way of defining subsets?
- Is "different coloured socks" not correct?
- Non-native English speakers struggle to come up with decent variable names and function names
- How can I get a list of locales in PostgreSQL?
- How to draw a line on an existing region using RegionPlot with manipulate?
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 .
Python 3: UnboundLocalError: local variable referenced before assignment
You can fix this by passing parameters rather than relying on Globals
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.
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.
Recent Posts

IMAGES
VIDEO
COMMENTS
UnboundLocalError: local variable 'x' referenced before assignment, solved UnboundLocalError in python, reason for UnboundLocalError in python, global vs nonlocal keyword in python
Python (3.3): UnboundLocalError: local variable referenced before assignment SOLVED By Paul Rooney: At the top of xcode put global of I have searched through other websites and throughout stacker overflow and cannot find a solution for this
The problem is that the variable context you created has the same name as the context you imported from multiprocessing at the top of the file
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
In Python, variables inside functions are considered local if and only if they appear in the left side of an assignment statement, or some other binding occurrence; otherwise such a binding is looked up in enclosing functions
Unboundlocalerror: local variable referenced before assignment is thrown if a variable is assigned before it's bound. Any variable assigned to a function's body is assumed to be a local variable unless explicitly declared as global
“UnboundLocalError: local variable referenced before assignment” after an if statement. I have also tried searching for the answer but I don't understand the answers to other people's similar problems
The problem I am having is that it is coming up with: UnboundLocalError: local variable ‘print' referenced before assignment and I don't know why
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)