Solving Python Error - UnboundLocalError: local variable 'x' referenced before assignment

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)

Solving python error - ValueError: invalid literal for int() with base 10

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.

enter image description here

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

Python Language

AI Code

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:

Got any Python Language Question?

pdf

Get monthly updates about new articles, cheatsheets, and tricks.

[SOLVED] Local Variable Referenced Before Assignment

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

[Fixed] SSL module in Python is Not Available

Local Variable Referenced Before Assignment Error with Explanation

Try these examples yourself using our Online Compiler.

Let’s look at the following function:

Local Variable Referenced Before Assignment Error

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

Mastering Python Translate: A Beginner’s Guide

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?

Karl Knechtel's user avatar

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.

wjandrea's user avatar

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 .

Dan H's user avatar

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:

javex's user avatar

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.

brandonsimpkins's user avatar

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.

Lali's user avatar

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"

Community's user avatar

To Solve this Error just initialize that variable above that loop or statement. For Example var a =""

Mihit Gandhi's user avatar

Not the answer you're looking for? Browse other questions tagged python or ask your own question .

Hot Network Questions

local variable referenced before assignment if statement

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

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

  1. Top 19 local variable 'x_1' referenced before assignment en iyi 2022

    local variable referenced before assignment if statement

  2. Top 19 local variable 'x_1' referenced before assignment en iyi 2022

    local variable referenced before assignment if statement

  3. Top 17 local variable referenced before assignment python global en iyi

    local variable referenced before assignment if statement

  4. UnboundLocalError: Local Variable Referenced Before Assignment

    local variable referenced before assignment if statement

  5. Top 19 local variable 'df' referenced before assignment en iyi 2022

    local variable referenced before assignment if statement

  6. Top 18 local variable 'w2' referenced before assignment en iyi 2022

    local variable referenced before assignment if statement

VIDEO

  1. VARIABLES AND DATA TYPES AND ASSIGNMENT STATEMENT IN VISUAL BASIC NET CHAPTER 1 PART 1

  2. (Unity URP) Game Environment Portfolio 2022 / Kowloon Walled City / 360 Video / By Calvin Ip

  3. Classes Objects as Parameters

  4. Function Call by Reference in C++

  5. before assignment submission

  6. Boys before assignment submission.#iit #iitdharwad #iitjee #iitmotivation

COMMENTS

  1. Solving Python Error

    UnboundLocalError: local variable 'x' referenced before assignment, solved UnboundLocalError in python, reason for UnboundLocalError in python, global vs nonlocal keyword in python

  2. Python (3.3): UnboundLocalError: local variable referenced before assignment

    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

  3. UnboundLocalError local variable 'context' referenced before assignment Django

    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

  4. python

    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

  5. Python Language Tutorial => Global Variables

    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

  6. [SOLVED] Local Variable Referenced Before Assignment

    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

  7. python

    “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

  8. UnboundLocalError: local variable 'print' referenced before assignment?

    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

  9. Python 3: UnboundLocalError: local variable referenced before assignment

    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)