- Python Basics
- Interview Questions
- Python Quiz
- Popular Packages
- Python Projects
- Practice Python
- AI With Python
- Learn Python3
- Python Automation
- Python Web Dev
- DSA with Python
- Python OOPs
- Dictionaries
UnboundLocalError Local variable Referenced Before Assignment in Python
Handling errors is an integral part of writing robust and reliable Python code. One common stumbling block that developers often encounter is the "UnboundLocalError" raised within a try-except block. This error can be perplexing for those unfamiliar with its nuances but fear not – in this article, we will delve into the intricacies of the UnboundLocalError and provide a comprehensive guide on how to effectively use try-except statements to resolve it.
What is UnboundLocalError Local variable Referenced Before Assignment in Python?
The UnboundLocalError occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.
Why does UnboundLocalError: Local variable Referenced Before Assignment Occur?
below, are the reasons of occurring "Unboundlocalerror: Try Except Statements" in Python :
Variable Assignment Inside Try Block
Reassigning a global variable inside except block.
- Accessing a Variable Defined Inside an If Block
In the below code, example_function attempts to execute some_operation within a try-except block. If an exception occurs, it prints an error message. However, if no exception occurs, it prints the value of the variable result outside the try block, leading to an UnboundLocalError since result might not be defined if an exception was caught.
In below code , modify_global function attempts to increment the global variable global_var within a try block, but it raises an UnboundLocalError. This error occurs because the function treats global_var as a local variable due to the assignment operation within the try block.
Solution for UnboundLocalError Local variable Referenced Before Assignment
Below, are the approaches to solve "Unboundlocalerror: Try Except Statements".
Initialize Variables Outside the Try Block
Avoid reassignment of global variables.
In modification to the example_function is correct. Initializing the variable result before the try block ensures that it exists even if an exception occurs within the try block. This helps prevent UnboundLocalError when trying to access result in the print statement outside the try block.
Below, code calculates a new value ( local_var ) based on the global variable and then prints both the local and global variables separately. It demonstrates that the global variable is accessed directly without being reassigned within the function.
In conclusion , To fix "UnboundLocalError" related to try-except statements, ensure that variables used within the try block are initialized before the try block starts. This can be achieved by declaring the variables with default values or assigning them None outside the try block. Additionally, when modifying global variables within a try block, use the `global` keyword to explicitly declare them.
Similar Reads
- Python Programs
- Python Errors
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
How to fix UnboundLocalError: local variable 'x' referenced before assignment in Python
by Nathan Sebhastian
Posted on May 26, 2023
Reading time: 2 minutes
One error you might encounter when running Python code is:
This error commonly occurs when you reference a variable inside a function without first assigning it a value.
You could also see this error when you forget to pass the variable as an argument to your function.
Let me show you an example that causes this error and how I fix it in practice.
How to reproduce this error
Suppose you have a variable called name declared in your Python code as follows:
Next, you created a function that uses the name variable as shown below:
When you execute the code above, you’ll get this error:
This error occurs because you both assign and reference a variable called name inside the function.
Python thinks you’re trying to assign the local variable name to name , which is not the case here because the original name variable we declared is a global variable.
How to fix this error
To resolve this error, you can change the variable’s name inside the function to something else. For example, name_with_title should work:
As an alternative, you can specify a name parameter in the greet() function to indicate that you require a variable to be passed to the function.
When calling the function, you need to pass a variable as follows:
This code allows Python to know that you intend to use the name variable which is passed as an argument to the function as part of the newly declared name variable.
Still, I would say that you need to use a different name when declaring a variable inside the function. Using the same name might confuse you in the future.
Here’s the best solution to the error:
Now it’s clear that we’re using the name variable given to the function as part of the value assigned to name_with_title . Way to go!
The UnboundLocalError: local variable 'x' referenced before assignment occurs when you reference a variable inside a function before declaring that variable.
To resolve this error, you need to use a different variable name when referencing the existing variable, or you can also specify a parameter for the function.
I hope this tutorial is useful. See you in other tutorials.
Take your skills to the next level ⚡️
I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.
Learn more about this website
Connect with me on Twitter
Or LinkedIn
Type the keyword below and hit enter
Click to see all tutorials tagged with:
Local variable referenced before assignment in Python
Last updated: Apr 8, 2024 Reading time · 4 min
# 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.
Make sure you don't try to access the variable before using the global keyword, otherwise, you'd get the SyntaxError: name 'X' is used prior to global declaration 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.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- SyntaxError: name 'X' is used prior to global declaration
Borislav Hadzhiev
Web Developer
Copyright © 2024 Borislav Hadzhiev
Top 2 Methods to Solve the ‘Local Variable Referenced Before Assignment’ Error in Python
Table of Contents
When working with Python, encountering the UnboundLocalError can be quite common, especially when dealing with variables that you intend to access globally within a function. This error typically occurs when a variable is referenced before it has been assigned a value within the local scope.
The Problem: Local Variable Referenced Before Assignment
Consider the following example:
Running the code above yields the error:
The critical point here is whether the variable test1 is recognized as global or local. In this case, Python reinterprets test1 as a local variable due to the attempted modification with += , which leads to confusion when it’s referenced before being assigned any value in the local scope.
So how can you resolve this issue effectively without passing test1 as an argument into test_func ? Let’s explore two main methods to approach this.
Method 1: Avoiding Globals
The best practice suggests minimizing the use of global variables. Instead of modifying a global variable directly, consider passing the variable to a function. Here’s how you could rewrite the example to avoid using a global variable entirely:
In this example, test_func takes a parameter x , performs the operation, and returns the modified value, allowing us to keep the variable scope clean.
Method 2: Declaring a Variable as Global
If modifying a global variable within a function is necessary, use the global keyword. Here’s how you can clarify that test1 should be treated as a global variable within test_func :
By using global test1 , you inform Python of your intention to operate on the global instance of test1 , thus eliminating the UnboundLocalError .
Further Alternatives
While the two methods outlined above are the most straightforward solutions, you can also consider using classes to encapsulate your variables and methods, managing state more formally through object-oriented programming. Here’s a simple example:
This alternative approach provides a structured way to manage your variables, improving code readability and maintainability.
FAQs on Top 2 Methods to Solve the ‘Local Variable Referenced Before Assignment’ Error in Python
Q: what is unboundlocalerror in python, q: how can i avoid using global variables in python, q: does using the global keyword affect performance, q: what are the best practices for variable scope in python.
For additional resources on Python programming, you might find W3Schools Python Tutorials and Geeks for Geeks Python Programming useful.
Fixing Python UnboundLocalError: Local Variable ‘x’ Accessed Before Assignment
Last updated: December 31, 2023
Table of Contents
Understanding unboundlocalerror, method 1: initializing the variable, method 2: using global variables, method 3: using nonlocal variables.
The UnboundLocalError in Python occurs when a function tries to access a local variable before it has been assigned a value. Variables in Python have scope that defines their level of visibility throughout the code: global scope, local scope, and nonlocal (in nested functions) scope. This error typically surfaces when using a variable that has not been initialized in the current function’s scope or when an attempt is made to modify a global variable without proper declaration.
Solutions for the Problem
To fix an UnboundLocalError, you need to identify the scope of the problematic variable and ensure it is correctly used within that scope.
Make sure to initialize the variable within the function before using it. This is often the simplest fix.
If you intend to use a global variable and modify its value within a function, you must declare it as global before you use it.
If the variable is defined in an outer function and you want to modify it within a nested function, use the nonlocal keyword.
That’s it. Happy coding!
Next Article: Fixing Python TypeError: Descriptor ‘lower’ for ‘str’ Objects Doesn’t Apply to ‘dict’ Object
Previous Article: Fixing the ValueError: Too Many Values to Unpack (Expected 2) in Python
Series: Common Errors in Python and How to Fix Them
Related Articles
Python: How to Convert a Dictionary to a Query String
February 12, 2024
Python File Modes: Explained
August 27, 2023
Python & aiohttp: How to download files using streams
August 20, 2023
Using aiohttp to make POST requests in Python (with examples)
Python asyncio.Queue class (with 3 examples)
August 18, 2023
How to Setup Python Virtual Environments (venv)
August 11, 2023
Python: Handling asyncio.exceptions.CancelledError gracefully
August 02, 2023
Python asyncio.wait_for() function (with examples)
Python Linked Lists: Explanation & Examples
July 31, 2023
Python asyncio.wait() function (with examples)
July 26, 2023
Python asyncio.gather() function (with examples)
Python match/case statement (with examples)
July 18, 2023
You May Also Like
- Python Warning: Secure coding is not enabled for restorable state
- Python TypeError: write() argument must be str, not bytes
- 4 ways to install Python modules on Windows without admin rights
- Python TypeError: object of type ‘NoneType’ has no len()
- Python: How to access command-line arguments (3 approaches)
- Understanding ‘Never’ type in Python 3.11+ (5 examples)
- Python: 3 Ways to Retrieve City/Country from IP Address
- Using Type Aliases in Python: A Practical Guide (with Examples)
- Python: Defining distinct types using NewType class
- Using Optional Type in Python (explained with examples)
- Python: How to Override Methods in Classes
- Python: Define Generic Types for Lists of Nested Dictionaries
- Python: Defining type for a list that can contain both numbers and strings
- Using TypeGuard in Python (Python 3.10+)
- Python: Using ‘NoReturn’ type with functions
- Type Casting in Python: The Ultimate Guide (with Examples)
- Python: Using type hints with class methods and properties
- Python: Typing a function with default parameters
- Python: Typing a function that can return multiple types
- Python: Typing a function with *args and **kwargs
Explore your training options in 10 minutes Get Started
- Graduate Stories
- Partner Spotlights
- Bootcamp Prep
- Bootcamp Admissions
- University Bootcamps
- Coding Tools
- Software Engineering
- Web Development
- Data Science
- Tech Guides
- Tech Resources
- Career Advice
- Online Learning
- Internships
- Apprenticeships
- Tech Salaries
- Associate Degree
- Bachelor's Degree
- Master's Degree
- University Admissions
- Best Schools
- Certifications
- Bootcamp Financing
- Higher Ed Financing
- Scholarships
- Financial Aid
- Best Coding Bootcamps
- Best Online Bootcamps
- Best Web Design Bootcamps
- Best Data Science Bootcamps
- Best Technology Sales Bootcamps
- Best Data Analytics Bootcamps
- Best Cybersecurity Bootcamps
- Best Digital Marketing Bootcamps
- Los Angeles
- San Francisco
- Browse All Locations
- Digital Marketing
- Machine Learning
- See All Subjects
- Bootcamps 101
- Full-Stack Development
- Career Changes
- View all Career Discussions
- Mobile App Development
- Cybersecurity
- Product Management
- UX/UI Design
- What is a Coding Bootcamp?
- Are Coding Bootcamps Worth It?
- How to Choose a Coding Bootcamp
- Best Online Coding Bootcamps and Courses
- Best Free Bootcamps and Coding Training
- Coding Bootcamp vs. Community College
- Coding Bootcamp vs. Self-Learning
- Bootcamps vs. Certifications: Compared
- What Is a Coding Bootcamp Job Guarantee?
- How to Pay for Coding Bootcamp
- Ultimate Guide to Coding Bootcamp Loans
- Best Coding Bootcamp Scholarships and Grants
- Education Stipends for Coding Bootcamps
- Get Your Coding Bootcamp Sponsored by Your Employer
- GI Bill and Coding Bootcamps
- Tech Intevriews
- Our Enterprise Solution
- Connect With Us
- Publication
- Reskill America
- Partner With Us
- Resource Center
- Bachelor’s Degree
- Master’s Degree
Python local variable referenced before assignment Solution
When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. This error is raised when you try to use a variable before it has been assigned in the local context .
In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you understand how you can solve it.
Find your bootcamp match
What is unboundlocalerror: local variable referenced before assignment.
Trying to assign a value to a variable that does not have local scope can result in this error:
Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function , that variable is local. This is because it is assumed that when you define a variable inside a function you only need to access it inside that function.
There are two variable scopes in Python: local and global. Global variables are accessible throughout an entire program; local variables are only accessible within the function in which they are originally defined.
Let’s take a look at how to solve this error.
An Example Scenario
We’re going to write a program that calculates the grade a student has earned in class.
We start by declaring two variables:
These variables store the numerical and letter grades a student has earned, respectively. By default, the value of “letter” is “F”. Next, we write a function that calculates a student’s letter grade based on their numerical grade using an “if” statement :
Finally, we call our function:
This line of code prints out the value returned by the calculate_grade() function to the console. We pass through one parameter into our function: numerical. This is the numerical value of the grade a student has earned.
Let’s run our code and see what happens:
An error has been raised.
The Solution
Our code returns an error because we reference “letter” before we assign it.
We have set the value of “numerical” to 42. Our if statement does not set a value for any grade over 50. This means that when we call our calculate_grade() function, our return statement does not know the value to which we are referring.
We do define “letter” at the start of our program. However, we define it in the global context. Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.
We solve this problem in two ways. First, we can add an else statement to our code. This ensures we declare “letter” before we try to return it:
Let’s try to run our code again:
Our code successfully prints out the student’s grade.
If you are using an “if” statement where you declare a variable, you should make sure there is an “else” statement in place. This will make sure that even if none of your if statements evaluate to True, you can still set a value for the variable with which you are going to work.
Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our calculate_grade() function. However, this approach is likely to lead to more confusing code and other issues. In general, variables should not be declared using “global” unless absolutely necessary . Your first, and main, port of call should always be to make sure that a variable is correctly defined.
In the example above, for instance, we did not check that the variable “letter” was defined in all use cases.
That’s it! We have fixed the local variable error in our code.
The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.
Now you’re ready to solve UnboundLocalError Python errors like a professional developer !
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .
What's Next?
Get matched with top bootcamps
Ask a question to our community, take our careers quiz.
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Understanding UnboundLocalError in Python
If you're closely following the Python tag on StackOverflow , you'll notice that the same question comes up at least once a week. The question goes on like this:
Why, when run, this results in the following error:
There are a few variations on this question, with the same core hiding underneath. Here's one:
Running the lst.append(5) statement successfully appends 5 to the list. However, substitute it for lst += [5] , and it raises UnboundLocalError , although at first sight it should accomplish the same.
Although this exact question is answered in Python's official FAQ ( right here ), I decided to write this article with the intent of giving a deeper explanation. It will start with a basic FAQ-level answer, which should satisfy one only wanting to know how to "solve the damn problem and move on". Then, I will dive deeper, looking at the formal definition of Python to understand what's going on. Finally, I'll take a look what happens behind the scenes in the implementation of CPython to cause this behavior.
The simple answer
As mentioned above, this problem is covered in the Python FAQ. For completeness, I want to explain it here as well, quoting the FAQ when necessary.
Let's take the first code snippet again:
So where does the exception come from? Quoting the FAQ:
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.
But x += 1 is similar to x = x + 1 , so it should first read x , perform the addition and then assign back to x . As mentioned in the quote above, Python considers x a variable local to foo , so we have a problem - a variable is read (referenced) before it's been assigned. Python raises the UnboundLocalError exception in this case [1] .
So what do we do about this? The solution is very simple - Python has the global statement just for this purpose:
This prints 11 , without any errors. The global statement tells Python that inside foo , x refers to the global variable x , even if it's assigned in foo .
Actually, there is another variation on the question, for which the answer is a bit different. Consider this code:
This kind of code may come up if you're into closures and other techniques that use Python's lexical scoping rules. The error this generates is the familiar UnboundLocalError . However, applying the "global fix":
Doesn't help - another error is generated: NameError: global name 'x' is not defined . Python is right here - after all, there's no global variable named x , there's only an x in external . It may be not local to internal , but it's not global. So what can you do in this situation? If you're using Python 3, you have the nonlocal keyword. Replacing global by nonlocal in the last snippet makes everything work as expected. nonlocal is a new statement in Python 3, and there is no equivalent in Python 2 [2] .
The formal answer
Assignments in Python are used to bind names to values and to modify attributes or items of mutable objects. I could find two places in the Python (2.x) documentation where it's defined how an assignment to a local variable works.
One is section 6.2 "Assignment statements" in the Simple Statements chapter of the language reference:
Assignment of an object to a single target is recursively defined as follows. If the target is an identifier (name): If the name does not occur in a global statement in the current code block: the name is bound to the object in the current local namespace. Otherwise: the name is bound to the object in the current global namespace.
Another is section 4.1 "Naming and binding" of the Execution model chapter:
If a name is bound in a block, it is a local variable of that block. [...] When a name is used in a code block, it is resolved using the nearest enclosing scope. [...] If the name refers to a local variable that has not been bound, a UnboundLocalError exception is raised.
This is all clear, but still, another small doubt remains. All these rules apply to assignments of the form var = value which clearly bind var to value . But the code snippets we're having a problem with here have the += assignment. Shouldn't that just modify the bound value, without re-binding it?
Well, no. += and its cousins ( -= , *= , etc.) are what Python calls " augmented assignment statements " [ emphasis mine ]:
An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target . The target is only evaluated once. An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead. With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments . Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.
So when earlier I said that x += 1 is similar to x = x + 1 , I wasn't telling all the truth, but it was accurate with respect to binding. Apart for possible optimization, += counts exactly as = when binding is considered. If you think carefully about it, it's unavoidable, because some types Python works with are immutable. Consider strings, for example:
The first line binds x to the value "abc". The second line doesn't modify the value "abc" to be "abcdef". Strings are immutable in Python . Rather, it creates the new value "abcdef" somewhere in memory, and re-binds x to it. This can be seen clearly when examining the object ID for x before and after the += :
Note that some types in Python are mutable. For example, lists can actually be modified in-place:
id(y) didn't change after += , because the object y referenced was just modified. Still, Python re-bound y to the same object [3] .
The "too much information" answer
This section is of interest only to those curious about the implementation internals of Python itself.
One of the stages in the compilation of Python into bytecode is building the symbol table [4] . An important goal of building the symbol table is for Python to be able to mark the scope of variables it encounters - which variables are local to functions, which are global, which are free (lexically bound) and so on.
When the symbol table code sees a variable is assigned in a function, it marks it as local. Note that it doesn't matter if the assignment was done before usage, after usage, or maybe not actually executed due to a condition in code like this:
We can use the symtable module to examine the symbol table information gathered on some Python code during compilation:
This prints:
So we see that x was marked as local in foo . Marking variables as local turns out to be important for optimization in the bytecode, since the compiler can generate a special instruction for it that's very fast to execute. There's an excellent article here explaining this topic in depth; I'll just focus on the outcome.
The compiler_nameop function in Python/compile.c handles variable name references. To generate the correct opcode, it queries the symbol table function PyST_GetScope . For our x , this returns a bitfield with LOCAL in it. Having seen LOCAL , compiler_nameop generates a LOAD_FAST . We can see this in the disassembly of foo :
The first block of instructions shows what x += 1 was compiled to. You will note that already here (before it's actually assigned), LOAD_FAST is used to retrieve the value of x .
This LOAD_FAST is the instruction that will cause the UnboundLocalError exception to be raised at runtime, because it is actually executed before any STORE_FAST is done for x . The gory details are in the bytecode interpreter code in Python/ceval.c :
Ignoring the macro-fu for the moment, what this basically says is that once LOAD_FAST is seen, the value of x is obtained from an indexed array of objects [5] . If no STORE_FAST was done before, this value is still NULL , the if branch is not taken [6] and the exception is raised.
You may wonder why Python waits until runtime to raise this exception, instead of detecting it in the compiler. The reason is this code:
Suppose something_true is a function that returns True , possibly due to some user input. In this case, x = 1 binds x locally, so the reference to it in x += 1 is no longer unbound. This code will then run without exceptions. Of course if something_true actually turns out to return False , the exception will be raised. Python has no way to resolve this at compile time, so the error detection is postponed to runtime.
For comments, please send me an email .
- Password Generator
- HTML Editor
- HTML Encoder
- JSON Beautifier
- CSS Beautifier
- Markdown Convertor
- Find the Closest Tailwind CSS Color
- Phrase encrypt / decrypt
- Browser Feature Detection
- Number convertor
- CSS Maker text shadow
- CSS Maker Text Rotation
- CSS Maker Out Line
- CSS Maker RGB Shadow
- CSS Maker Transform
- CSS Maker Font Face
- Color Picker
- Colors CMYK
- Color mixer
- Color Converter
- Color Contrast Analyzer
- Color Gradient
- String Length Calculator
- MD5 Hash Generator
- Sha256 Hash Generator
- String Reverse
- URL Encoder
- URL Decoder
- Base 64 Encoder
- Base 64 Decoder
- Extra Spaces Remover
- String to Lowercase
- String to Uppercase
- Word Count Calculator
- Empty Lines Remover
- HTML Tags Remover
- Binary to Hex
- Hex to Binary
- Rot13 Transform on a String
- String to Binary
- Duplicate Lines Remover
Python 3: UnboundLocalError: local variable referenced before assignment
This error occurs when you are trying to access a variable before it has been assigned a value. Here is an example of a code snippet that would raise this error:
Watch a video course Python - The Practical Guide
The error message will be:
In this example, the variable x is being accessed before it is assigned a value, which is causing the error. To fix this, you can either move the assignment of the variable x before the print statement, or give it an initial value before the print statement.
Both will work without any error.
Related Resources
- Using global variables in a function
- "Least Astonishment" and the Mutable Default Argument
- Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
- HTML Basics
- Javascript Basics
- TypeScript Basics
- React Basics
- Angular Basics
- Sass Basics
- Vue.js Basics
- Python Basics
- Java Basics
- NodeJS Basics
IMAGES
VIDEO
COMMENTS
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.
What is UnboundLocalError: Local variable Referenced Before Assignment? This error occurs when a local variable is referenced before it has been assigned a value within a function or method.
What is UnboundLocalError Local variable Referenced Before Assignment in Python? The UnboundLocalError occurs when a local variable is referenced before it has been assigned a value within a function or method.
The UnboundLocalError: local variable 'x' referenced before assignment occurs when you reference a variable inside a function before declaring that variable. To resolve this error, you need to use a different variable name when referencing the existing variable, or you can also specify a parameter for the function.
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 'test1' referenced before assignment. The critical point here is whether the variable test1 is recognized as global or local. In this case, Python reinterprets test1 as a local variable due to the attempted modification with += , which leads to confusion when it’s referenced before being assigned any value in ...
To fix an UnboundLocalError, you need to identify the scope of the problematic variable and ensure it is correctly used within that scope. Method 1: Initializing the Variable. Make sure to initialize the variable within the function before using it. This is often the simplest fix. Method 2: Using Global Variables
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.
As mentioned in the quote above, Python considers x a variable local to foo, so we have a problem - a variable is read (referenced) before it's been assigned. Python raises the UnboundLocalError exception in this case [1] .
UnboundLocalError: local variable 'x' referenced before assignment. In this example, the variable x is being accessed before it is assigned a value, which is causing the error. To fix this, you can either move the assignment of the variable x before the print statement, or give it an initial value before the print statement.