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

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

Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
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?

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

Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *

- 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
- Developers think AI assistants will be everywhere, but aren’t sure how to...
- Visible APIs get reused, not reinvented sponsored post
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Will the tree roots of a wrapped root ball above ground be harmed by freezing temperatures?
- What's the earliest fictional work of literature that contains an allusion to an earlier fictional work of literature?
- What is the most air-tight substance an organism can produce?
- How do you handle giving an invited university talk in a smaller room compared to previous speakers?
- How much technical / debugging help should I expect my advisor to provide?
- Portable Alternatives to Traditional Keyboard/Mouse Input
- Why does cat with no argument read from standard input?
- Using vegetable peelings to make stock
- H-Bridge blows the fuses in my house
- Including somebody with an unrelated degree as a coauthor?
- Fantasy novel where magic has a cost and it transforms a female character into a monster
- What if you could shut off the pull of gravity on your body?
- What's better than \emph for making my Latin terms italic?
- Who was Abraham’s Mother?
- Training for driving on the left in the UK
- Mechanic sent me this image and said my brake rotors should be replaced. Does this seem right?
- Can a bank sue someone that starts a bank run that destroys the bank?
- A question about paladin oath spells
- Why are sulfites often ignored in soil studies?
- Can a whisper protect a crewmate from the supernatural terror consequence of a compelled spirit?
- Is it traversable?
- Trying to find a short story about criminals who are given implants so they can be controlled by aliens
- I have to pay back my student loan. When is the best time to do it?
- Is it a valid chemical?
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 .

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.

Explanation:
In the above example, we have given the value of variable “v1” in two places.
- Outside the function “myfunction()” .
- And at the end of the function “myfunction()” .
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
- Pass parameters with the function
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
- Python Online Compiler
- pip is not recognized
- Python Min()
- Armstrong Number in Python
- Python map()
- Polymorphism in Python
- Inheritance in Python
- Python Pass Statement
- Python Range
- Python String Title() Method
- Python Split()
- Reverse Words in a String Python
- Area of Circle in Python
- Python Reverse String
- Attribute Error Python
- Python Combine Lists
- Python list append and extend
- Python Sort Dictionary by Key or Value
- indentationerror: unindent does not match any outer indentation level in Python
- Python KeyError
- Learn Python Programming
- Python Training Tutorials for Beginners
- Square Root in Python
- Addition of two numbers in Python
- Null Object in Python
- Python vs PHP
- TypeError: 'int' object is not subscriptable
- Python Comment
- Python Factorial
- Python Continue Statement
- Python lowercase
- Python Uppercase
- Python String Replace
- Python String find
- Python Max() Function
- Invalid literal for int() with base 10 in Python
- Top Online Python Compiler
- Python : end parameter in print()
- Python String Concatenation
- Python Enumerate
- Python New 3.6 Features
- Python input()
- Python String Contains
- Python eval
- Python zip()
- Install Opencv Python PIP Windows
- String Index Out of Range Python
- Python Print Without Newline
- Id() function in Python
- Ord Function in Python
- Only Size-1 Arrays Can be Converted to Python Scalars
- Bubble Sort in Python
- Python slice() function
- Convert List to String Python
- Remove Punctuation Python
- Compare Two Lists in Python
- Python Infinity
- Python Return Outside Function
- Pangram Program 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

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

Borislav Hadzhiev
Reading time · 4 min

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 .

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:
- Becomes local to the scope.
- Shadows any variables from the outer scope that have the same name.
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 a variable is only referenced inside a function, it is implicitly global.
- If a variable is assigned a value inside a function's body, it is assumed to be local, unless explicitly marked as global .
If you want to read more about why this error occurs, check out [this section] ( this section ) of the docs.

Web Developer

Copyright © 2023 Borislav Hadzhiev
[SOLVED] Local Variable Referenced Before Assignment

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

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

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

UnboundLocalError Local Variable 'index' 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:
- Debugging Python errors
- How Grofers meets unprecedented delivery demand
- Getting started with a Python SDK (docs)
Related Answers
- Accessing the Index in a `for` Loop in Python
- Difference between `@staticmethod` and `@classmethod` function decorators in Python
- How to manage feature flags without making performance worse
- How do I parse a string to a float or int?
- What does `if __name__ == "__main__":` do?
- Is There a List of pytz Timezones?
- Making a list out of a list of lists in Python?
- Add new keys to a dictionary in Python
- Sort a dictionary by value in Python
- Iterate over a dictionary in Python
- List files in a directory using Python
- How Do I Merge Two Dictionaries in a Single Expression (Take Union of Dictionaries)?
- How Can I Safely Create a Nested Directory?
- Python slice notation
- Does Python Have a Ternary Conditional Operator?
- What Does the `yield` Keyword in Python Do?
- Running External Programs in Python
- TypeError 'str' Object Does Not Support Item Assignment
- Upgrade specific `pip` packages in Python
- What are Python Metaclasses?
A better experience for your users. An easier life for your developers.
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

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

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:
- We have declared the variable num =5 .
- Defined a function calculate() in which we have i ncreased the num variable by 1 and stored it in the variable itself.
- Printed the num value.
- Called the function to calculate.
Error Output:

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:

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.

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 .
- Oracle Hiring for Python internship 2023: Apply Now
- Capgemini hiring freshers and experienced in bulk with CTC 5-15 LPA. Apply now!
- IIT Kanpur’s Python Learning Program: Apply Now
- Microsoft Giving Free Machine Learning Course: Enroll Now
- Accenture Giving Free Developer Certificate in 2023
- Microsoft Bing Eating Google Traffic: Check results here
- ChatGPT 4 with videos next week: Unveiled by Microsoft
- DevSecOps Internship at IBM: Apply Now
- Python Internship at Cisco: Apply Now
- Python Internship at HP: Apply Now
- Python | Asking the user for input until they give a valid response
- Python Internship at Lenovo: Apply Now
- Amazon Summer Internship 2023
- Amazon Giving Free Machine Learning Course with Certificate: Enroll Now
- Elon Musk hiring AI researchers to develop OpenAI rival
- Why Elon Musk Quits OpenAI?
- Google Summer Internship 2023
- 5 Secret ChatGPT skills to make money
- Free Google Certification Courses
- 5 AI tools for coders better than ChatGPT
- New secrets to Earn money with Python in 2023
- How to utilize ChatGPT to improve your coding skills?
- Create your own ChatGPT with Python
- Bakery Management System in Python | Class 12 Project
- SQLite | CRUD Operations in Python
- Event Management System Project in Python
- Ticket Booking and Management in Python
- Radha Krishna using Python Turtle
- Hostel Management System Project in Python
- Sales Management System Project in Python
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
- 100+ Python Projects
- 100+ Java Projects
- Python Programs
- JavaScript Projects
- Java Projects
- PHP Projects
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
VIDEO
COMMENTS
The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before 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 · 1.
The “local variable referenced before assignment” error occurs when you give reference of a local variable without assigning any value. Example:
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
The local variable referenced before assignment occurs when some variable is referenced before assignment within a function's body.
The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a
Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the
The exception UnboundLocalError: local variable 'index' referenced before assignment happens in Python when you use a global variable in a
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the
The error UnboundLocalError: local variable referenced before assignment occurs because we try to assign a value to the variable that does not