local variable 'response' referenced before assignment

Explore your training options in 10 minutes Get Matched

  • 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
  • Web Development
  • Digital Marketing
  • Machine Learning
  • See All Subjects
  • Bootcamps 101
  • Data Science
  • Software Engineering
  • 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
  • Career Advice
  • Our Enterprise Solution
  • Connect With Us
  • Publication
  • Reskill America
  • Partner With Us

Career Karma

  • Resource Center
  • Graduate Stories
  • Partner Spotlights
  • Bootcamp Prep
  • Bootcamp Admissions
  • University Bootcamps
  • Coding Tools
  • Tech Guides
  • Tech Resources
  • 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

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.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

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?

icon_10

Get matched with top bootcamps

Ask a question to our community, take our careers quiz.

James Gallagher

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

local variable 'response' referenced before assignment

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 'response' referenced before assignment

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 .

Online Tutorials & Training Materials | STechies.com

UnboundLocalError: Local Variable Referenced Before Assignment

The “local variable referenced before assignment” error occurs when you give reference of a local variable without assigning any value.

local variable 'response' referenced before assignment

Explanation:

In the above example, we have given the value of variable “v1” in two places.

If we assign a value of a variable in the function it becomes local variable to that function, but in the above example we have assigned the value to “v1” variable at the end of the function and we are referring this variable before assigning.

And the variable “v1” which we have assigned at the beginning of the code block is not declared as a global variable.

To avoid an error like “UnboundLocalError: local variable referenced before assignment” to occur, we have to:

Declare Global Variable

Code example with global variable:

As we know if we declare any variable as global then its scope becomes global.

Pass function with Parameters

Code example passing parameters with function:

In the above example, as you can see, we are not using a global variable but passing the value of variable “v1” as a parameter with the function “myfunction()”.

Example 2.1

In the "example2 ", we have called a function “dayweek()” with parameter value “10” which gives the error but the same function with value “1” which runs properly in “example 2.1” and returns the output as “Weekday”.

Because in the above function we are assigning the value to variable “wd” if the value of variable " day " is the range from (0 to 7) . If the value of variable " day " greater than "7" or lower then " 0" we are not assigning any value to variable " wd " That's why, whenever the parameter is greater than 7 or less than 0, python compiler throws the error “ UnboundLocalError: local variable 'wd' referenced before assignment ”

To avoid such type of error you need assign the function variable which lies within the range or we need to assign some value like " Invalid Value " to variable " wd " if the value of variable " day " is not in range from ( 0 to 7 )

Correct Example with Exception

How to Fix Local Variable Referenced Before Assignment Error in Python

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.

Local Variable Referenced Before Assignment in Python

Local Variable Referenced Before Assignment in Python

The local variable referenced before assignment occurs when some variable is referenced before assignment within a function’s body. The error usually occurs when the code is trying to access the global variable. As the global variables have global scope and can be accessed from anywhere within the program, the user usually tries to use the global variable within a function.

the Solution of local variable referenced before assignment Error in Python

We can declare the variable as global using the global keyword in Python. Once the variable is declared global, the program can access the variable within a function, and no error will occur.

Please enable JavaScript

Local variable referenced before assignment in Python

avatar

Borislav Hadzhiev

Reading time · 4 min

banner

Photo from Unsplash

Local variable referenced before assignment in Python #

The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function.

To solve the error, mark the variable as global in the function definition, e.g. global my_var .

unboundlocalerror local variable name referenced before assignment

Here is an example of how the error occurs.

We assign a value to the name variable in the function.

Mark the variable as global to solve the error #

To solve the error, mark the variable as global in your function definition.

If a variable is assigned a value in a function's body, it is a local variable unless explicitly declared as global .

Local variables shadow global ones with the same name #

You could reference the global name variable from inside the function but if you assign a value to the variable in the function's body, the local variable shadows the global one.

Accessing the name variable in the function is perfectly fine.

On the other hand, variables declared in a function cannot be accessed from the global scope.

The name variable is declared in the function, so trying to access it from outside causes an error.

Returning a value from the function instead #

An alternative solution to using the global keyword is to return a value from the function and use the value to reassign the global variable.

We simply return the value that we eventually use to assign to the name global variable.

Passing the global variable as an argument to the function #

You should also consider passing the global variable as an argument to the function.

We passed the name global variable as an argument to the function.

If we assign a value to a variable in a function, the variable is assumed to be local unless explicitly declared as global .

Assigning a value to a local variable from an outer scope #

If you have a nested function and are trying to assign a value to the local variables from the outer function, use the nonlocal keyword.

The nonlocal keyword allows us to work with the local variables of enclosing functions.

Had we not used the nonlocal statement, the call to the print() function would have returned an empty string.

Printing the message variable on the last line of the function shows an empty string because the inner() function has its own scope.

Changing the value of the variable in the inner scope is not possible unless we use the nonlocal keyword.

Instead, the message variable in the inner function simply shadows the variable with the same name from the outer scope.

Discussion #

As shown in this section of the documentation, when you assign a value to a variable inside a function, the variable:

The last line in the example function assigns a value to the name variable, marking it as a local variable and shadowing the name variable from the outer scope.

At the time the print(name) line runs, the name variable is not yet initialized, which causes the error.

The most intuitive way to solve the error is to use the global keyword.

The global keyword is used to indicate to Python that we are actually modifying the value of the name variable from the outer scope.

If you want to read more about why this error occurs, check out [this section] ( this section ) of the docs.

book cover

Web Developer

buy me a coffee

Copyright © 2023 Borislav Hadzhiev

[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

Python Performance Showdown: Threading vs. Multiprocessing

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.

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

In-depth Guide to Master Python Shell Commands

UnboundLocalError Local Variable 'index' Referenced Before Assignment

local variable 'response' referenced before assignment

.css-13lojzj{position:absolute;padding-right:0.25rem;margin-left:-1.25rem;left:0;height:100%;display:-webkit-inline-box;display:-webkit-inline-flex;display:-ms-inline-flexbox;display:inline-flex;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;display:none;} .css-b94zdx{width:1rem;height:1rem;} The Problem

The exception UnboundLocalError: local variable 'index' referenced before assignment happens in Python when you use a global variable in a function that also defines a local version of the same variable.

Because index is defined globally as well as inside the foo() function, Python throws an exception if you try to use the variable inside foo before it’s declared.

The Solution

In this case either move the index declaration up higher in the foo function, or rename the variable to avoid the conflict.

Further Reading

If you’re looking to get a deeper understanding of how Python application monitoring works, take a look at the following articles:

Related Answers

A better experience for your users. An easier life for your developers.

VINTA BHARATH SAI REDDY

Jan 13, 2020

UnboundLocalError: local variable referenced before assignment in Python.

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.

works, but this code:

results in an UnboundLocalError:

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x , the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

In the example above you can access the outer scope variable by declaring it global:

This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:

You can do a similar thing in a nested scope using the nonlocal keyword:

global : This keyword is useful when we need to assign any value to global object inside any function. nonlocal : This keyword is useful when we need to assign any value to nested scope variable.

So friends, be little careful while playing with global object assignment in Python.

Happy Coding :-)

Thanks for reading! If you liked this article, hit that clap button below 👏. It means a lot to me and it helps other people see the story.

More from VINTA BHARATH SAI REDDY

About Help Terms Privacy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

VINTA BHARATH SAI REDDY

Text to speech

CopyAssignment

We are Python language experts, a community to solve Python problems, we are a 1.2 Million community on Instagram, now here to help with our blogs.

Local variable referenced before assignment Solved error in Python

Local variable referenced before assignment Solved error in Python

In this tutorial, we will be discussing why UnboundLocalError: local variable referenced before assignment occurs . When we used functions in our code we come across this type of error as we try to use a local variable referenced before the assignment. Here we will try to understand what this error means, why it is raised and how it can be resolved with the help of examples.

What is UnboundLocalError: local variable referenced before assignment?

In python, the scope of the variable is determined depending on whether the variable is defined inside the function or outside. If the variable is declared inside the function then its scope is within the function itself and we can access it inside the function only.

The error UnboundLocalError: local variable referenced before assignmen t occurs because we try to assign a value to the variable that does not have a local scope. As the global variable has a global scope the user tries to access to use the variable within the function.

There are two types of variables local variables and global variables.

Difference between local variables and global variables

The below example code demonstrates the code where the program will end up with the “local variable referenced before assignment” error.

Explanation:

Error Output:

Output 1 of UnboundLocalError: local variable referenced before assignment

What went wrong here?  We have declared the num variable outside the function while the function cannot access it until you declared it global using the global keyword.

Solution with the global keyword

Here we initialized the num variable with the global keyword so that it can be accessed inside and outside the function.

Resolved Output:

Output 2 of UnboundLocalError: local variable referenced before assignment

Solution with passing parameter

Here we can pass the parameter to the function so there is no need of declaring the variable as local or global. So the need for variable declaration is resolved.

Output 3 of UnboundLocalError: local variable referenced before assignment

Hence, in this article, we came to know the reasons for the error “UnboundLocalError: local variable referenced before assignment” . We have understood how the use of global keywords and passing the parameter solved this type of error.

For more articles on python keep visiting our website copyassignment.com

Thank you for visiting our website .

Avatar of pranjal dev

Author: pranjal dev

Search…..

Machine Learning

Data Structures and Algorithms(Python)

Python Turtle

Games with Python

All Blogs On-Site

Python Compiler(Interpreter)

Online Java Editor

Online C++ Editor

Online C Editor

All Editors

Services(Freelancing)

Recent Posts

RoadMap to Learn

Python handwritten notes.

Click Here to buy now

Python Assignment Help

We also deal with Python Assignments, Homeworks, and Projects. Click Here, to get your Python work done by experts.

© Copyright 2019-2023 www.copyassignment.com. All rights reserved. Developed by copyassignment

IMAGES

  1. Python Check If The Variable Is An Integer

    local variable 'response' referenced before assignment

  2. UnboundLocalError: local variable 'response' referenced before assignment

    local variable 'response' referenced before assignment

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

    local variable 'response' referenced before assignment

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

    local variable 'response' referenced before assignment

  5. python

    local variable 'response' referenced before assignment

  6. Local variable ‘ ‘ might be referenced before assignment_Mr_Wang_up的博客-程序员秘密

    local variable 'response' referenced before assignment

VIDEO

  1. L10 02 SharedPreferences Declare Variable

  2. processing ex59 more functions with parameters

  3. Module 4

  4. 1 day before Assignment submission 😂#college #mbbs #shorts #tarezameenpar #neet_motivation #medico

  5. vizualising priors; data-driven weakly-informed priors; inference for two independent groups

  6. 15 Template Reference Variable

COMMENTS

  1. Python local variable referenced before assignment Solution

    The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it

  2. "UnboundLocalError: local variable referenced before assignment

    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 · 1.

  3. UnboundLocalError: Local Variable Referenced Before Assignment

    The “local variable referenced before assignment” error occurs when you give reference of a local variable without assigning any value. Example:

  4. How to Fix Local Variable Referenced Before Assignment Error in

    In this post, we learned at how to avoid the local variable referenced before assignment error in Python. The error stems from trying to refer

  5. Local Variable Referenced Before Assignment in Python

    The local variable referenced before assignment occurs when some variable is referenced before assignment within a function's body.

  6. Local variable referenced before assignment in Python

    The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a

  7. [SOLVED] Local Variable Referenced Before Assignment

    Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the

  8. UnboundLocalError Local Variable 'index' Referenced Before

    The exception UnboundLocalError: local variable 'index' referenced before assignment happens in Python when you use a global variable in a

  9. UnboundLocalError: local variable referenced before assignment in

    In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the

  10. Local Variable Referenced Before Assignment Solved Error In Python

    The error UnboundLocalError: local variable referenced before assignment occurs because we try to assign a value to the variable that does not