Mar 29, 2024 · Hangup (SIGHUP) Traceback (most recent call last): File "Solution.py", line 7, in <module> example_function() File "Solution.py", line 4, in example_function x += 1 # Trying to modify global variable 'x' without declaring it as global UnboundLocalError: local variable 'x' referenced before assignment Solution for Local variable Referenced ... ... Apr 13, 2022 · Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the concept of variable declarations. Python does not have the concept of variable declarations. ... May 26, 2023 · 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. ... Apr 8, 2024 · # 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. ... Nov 6, 2024 · 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 ... ... Learn how to fix and prevent unbound local errors in your Python code. This comprehensive guide will provide you with the necessary tools to troubleshoot and debug your code, ensuring that your programs run smoothly and without any errors. From understanding the root cause of unbound local errors to implementing best practices for variable assignment, this guide has you covered. ... 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. def example (): x = 5 print (x) example() ... Dec 31, 2023 · 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. 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. Method 3: Using Nonlocal Variables ... What is Scope in Python? Scope refers to a variable being only available inside the region where it was created. A variable created inside a function belongs to the local scope of that function, and we can only use that variable inside that function. ... ">
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs

How to Fix - UnboundLocalError: Local variable Referenced Before Assignment in Python

Developers often encounter the  UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches.

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

Below, are the reasons by which UnboundLocalError: Local variable Referenced Before Assignment error occurs in  Python :

Nested Function Variable Access

Global variable modification.

In this code, the outer_function defines a variable 'x' and a nested inner_function attempts to access it, but encounters an UnboundLocalError due to a local 'x' being defined later in the inner_function.

In this code, the function example_function tries to increment the global variable 'x', but encounters an UnboundLocalError since it's treated as a local variable due to the assignment operation within the function.

Solution for Local variable Referenced Before Assignment in Python

Below, are the approaches to solve “Local variable Referenced Before Assignment”.

In this code, example_function successfully modifies the global variable 'x' by declaring it as global within the function, incrementing its value by 1, and then printing the updated value.

In this code, the outer_function defines a local variable 'x', and the inner_function accesses and modifies it as a nonlocal variable, allowing changes to the outer function's scope from within the inner function.

Similar Reads

  • How to Fix - UnboundLocalError: Local variable Referenced Before Assignment in Python Developers often encounter the UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches. What is UnboundLocalError: Local variable Re 3 min read
  • 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, w 4 min read
  • How to Access Dictionary Values in Python Using For Loop A dictionary is a built-in data type in Python designed to store key-value pairs of data. The most common method to access values in Python is through the use of a for loop. This article explores various approaches to accessing values in a dictionary using a for loop. Access Dictionary Values in Pyt 2 min read
  • How to fix "SyntaxError: invalid character" in Python In this article, we will understand the SyntaxError: invalid character in Python through examples, and we will also explore potential approaches to resolve this issue. What is "SyntaxError: invalid character" in Python?Python SyntaxError: Invalid Character occurs when the interpreter encounters a ch 3 min read
  • Python | Accessing variable value from code scope Sometimes, we just need to access a variable other than the usual way of accessing by it's name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let's ta 3 min read
  • How To Fix - Python RuntimeWarning: overflow encountered in scalar One such error that developers may encounter is the "Python RuntimeWarning: Overflow Encountered In Scalars". In Python, numeric operations can sometimes trigger a "RuntimeWarning: overflow encountered in a scalar." In this article, we will see what is Python "Python Runtimewarning: Overflow Encount 3 min read
  • Different Forms of Assignment Statements in Python We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object. There are some important properties of assignment in Python :- 3 min read
  • Python Program to Find and Print Address of Variable In this article, we are going to see how to find and print the address of the Python variable. It can be done in these ways: Using id() functionUsing addressof() functionUsing hex() functionMethod 1: Find and Print Address of Variable using id()We can get an address using id() function, id() functio 2 min read
  • Accessing Python Function Variable Outside the Function In Python, variables defined within a function have local scope by default. But to Access function variables outside the function usually requires the use of the global keyword, but can we do it without using Global. In this article, we will see how to access a function variable outside the function 4 min read
  • Variables under the hood in Python In simple terms, variables are names attached to particular objects in Python. To create a variable, you just need to assign a value and then start using it. The assignment is done with a single equals sign (=): C/C++ Code # Variable named age age = 20 print(age) # Variable named id_number id_no = 4 3 min read
  • How to Change Class Attributes By Reference in Python We have the problem of how to change class attributes by reference in Python, we will see in this article how can we change the class attributes by reference in Python. What is Class Attributes?Class attributes are typically defined outside of any method within a class and are shared among all insta 3 min read
  • Python program to find number of local variables in a function Given a Python program, task is to find the number of local variables present in a function. Examples: Input : a = 1 b = 2.1 str = 'GeeksForGeeks' Output : 3 We can use the co_nlocals() function which returns the number of local variables used by the function to get the desired result. Code #1: # Im 1 min read
  • Python program to create dynamically named variables from user input Given a string input, our task is to write a Python program to create a variable from that input (as a variable name) and assign it to some value. Below are the methods to create dynamically named variables from user input. Using globals() method to create dynamically named variables Here we are usi 2 min read
  • Python TabError: Inconsistent Use of Tabs and Spaces in Indentation Python, known for its readability and simplicity, enforces strict indentation rules to structure code. However, encountering a TabError can be frustrating, especially when the code appears to be properly aligned. In this article, we'll explore what a TabError is, and how to resolve TabError in Pytho 2 min read
  • Insert a Variable into a String - Python In Python, inserting a variable inside a string is a common task. There are different ways to do this depending on which method you find easiest. Let’s look at some simple methods to insert variables into strings. Using + OperatorThe simplest way to insert a variable into a string is by using the + 1 min read
  • Python | Using variable outside and inside the class and method In Python, we can define the variable outside the class, inside the class, and even inside the methods. Let's see, how to use and access these variables throughout the program. Variable defined outside the class: The variables that are defined outside the class can be accessed by any class or any me 3 min read
  • SyntaxError: ‘return’ outside function in Python We are given a problem of how to solve the 'Return Outside Function' Error in Python. In this article, we will see how to solve the 'Return Outside Function' Error in Python with reasons for it's occurring and also approaches to solve SyntaxError: ‘return’ outside function” in Python. What is Syntax 4 min read
  • Run One Python Script From Another in Python In Python, we can run one file from another using the import statement for integrating functions or modules, exec() function for dynamic code execution, subprocess module for running a script as a separate process, or os.system() function for executing a command to run another Python file within the 5 min read
  • Python | Scope resolution when a function is called or defined Python resolves the scope of the parameters of a function in two ways: When the function is definedWhen the function is called When the function is defined Consider this sample program which has a function adder(a, b) which adds an element a to the list b and returns the list b. The default value of 3 min read
  • Python Programs
  • Python Errors
  • Python How-to-fix

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

[SOLVED] Local Variable Referenced Before Assignment

local variable referenced before assignment

Python treats variables referenced only inside a function as global variables. Any variable assigned to a function’s body is assumed to be a local variable unless explicitly declared as global.

Why Does This Error Occur?

Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the concept of variable declarations. Hence it searches for the variable whenever used. When not found, it throws the error.

Before we hop into the solutions, let’s have a look at what is the global and local variables.

Local Variable Declarations vs. Global Variable Declarations

[Fixed] typeerror can’t compare datetime.datetime to datetime.date

Local Variable Referenced Before Assignment Error with Explanation

Try these examples yourself using our Online Compiler.

Let’s look at the following function:

Local Variable Referenced Before Assignment Error

Explanation

The variable myVar has been assigned a value twice. Once before the declaration of myFunction and within myFunction itself.

Using Global Variables

Passing the variable as global allows the function to recognize the variable outside the function.

Create Functions that Take in Parameters

Instead of initializing myVar as a global or local variable, it can be passed to the function as a parameter. This removes the need to create a variable in memory.

UnboundLocalError: local variable ‘DISTRO_NAME’

This error may occur when trying to launch the Anaconda Navigator in Linux Systems.

Upon launching Anaconda Navigator, the opening screen freezes and doesn’t proceed to load.

Try and update your Anaconda Navigator with the following command.

If solution one doesn’t work, you have to edit a file located at

After finding and opening the Python file, make the following changes:

In the function on line 159, simply add the line:

DISTRO_NAME = None

Save the file and re-launch Anaconda Navigator.

DJANGO – Local Variable Referenced Before Assignment [Form]

The program takes information from a form filled out by a user. Accordingly, an email is sent using the information.

Upon running you get the following error:

We have created a class myForm that creates instances of Django forms. It extracts the user’s name, email, and message to be sent.

A function GetContact is created to use the information from the Django form and produce an email. It takes one request parameter. Prior to sending the email, the function verifies the validity of the form. Upon True , .get() function is passed to fetch the name, email, and message. Finally, the email sent via the send_mail function

Why does the error occur?

We are initializing form under the if request.method == “POST” condition statement. Using the GET request, our variable form doesn’t get defined.

Local variable Referenced before assignment but it is global

This is a common error that happens when we don’t provide a value to a variable and reference it. This can happen with local variables. Global variables can’t be assigned.

This error message is raised when a variable is referenced before it has been assigned a value within the local scope of a function, even though it is a global variable.

Here’s an example to help illustrate the problem:

In this example, x is a global variable that is defined outside of the function my_func(). However, when we try to print the value of x inside the function, we get a UnboundLocalError with the message “local variable ‘x’ referenced before assignment”.

This is because the += operator implicitly creates a local variable within the function’s scope, which shadows the global variable of the same name. Since we’re trying to access the value of x before it’s been assigned a value within the local scope, the interpreter raises an error.

To fix this, you can use the global keyword to explicitly refer to the global variable within the function’s scope:

However, in the above example, the global keyword tells Python that we want to modify the value of the global variable x, rather than creating a new local variable. This allows us to access and modify the global variable within the function’s scope, without causing any errors.

Local variable ‘version’ referenced before assignment ubuntu-drivers

This error occurs with Ubuntu version drivers. To solve this error, you can re-specify the version information and give a split as 2 –

Here, p_name means package name.

With the help of the threading module, you can avoid using global variables in multi-threading. Make sure you lock and release your threads correctly to avoid the race condition.

When a variable that is created locally is called before assigning, it results in Unbound Local Error in Python. The interpreter can’t track the variable.

Therefore, we have examined the local variable referenced before the assignment Exception in Python. The differences between a local and global variable declaration have been explained, and multiple solutions regarding the issue have been provided.

Trending Python Articles

[Fixed] nameerror: name Unicode is not defined

How to fix UnboundLocalError: local variable 'x' referenced before assignment in Python

by Nathan Sebhastian

Posted on May 26, 2023

Reading time: 2 minutes

unboundlocalerror local variable 'job_id' referenced before assignment

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

avatar

Last updated: Apr 8, 2024 Reading time · 4 min

banner

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

mark variable as global

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 global variables in functions

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.

variables declared in function cannot be accessed in 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.

return value from the function

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.

pass global variable as argument to 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.

assign value to local variable from outer scope

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.

not using nonlocal prints 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

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

logo

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.

Profile Avatar

Need an Expert?

I have over 10 years of experience in coding. My journey began in 2014, starting with HTML, CSS, SQL, C#, and ASP.NET. In 2016, I expanded my skills with more...

ASP.NET WebForms and developed my first major project, a Recipe Maker Website. Over the years, I have embraced new technologies like Blazor, .NET Core, and Tailwind CSS, and I focus on creating modern, scalable web applications. I enjoy solving challenges, building clean, maintainable code, and collaborating on exciting projects. Currently, I focus on full stack interactive apps using Real-Time, AI powered using Blazor, Tailwind CSS and More. I'm always eager to learn and grow with new technologies.

studymite Logo

  • Fix: "syntax error: unexpected eof" while parsing Python input
  • Do streamers use VPNs?
  • Is a vpn worth it for torrenting?
  • Converting Uppercase to Lowercase in Python
  • Converting a Comma-Separated String to a List in Python - Multiple Approaches
  • Counting the Occurrences of Unique Values in a Python List: Multiple Approaches
  • Remove Special Characters from a String in Python Using Regex
  • Get File Size in Human Readable Format in Python
  • How to Get Current Time in Milliseconds, Seconds(epoch) Using Various Methods in Python
  • Find and Replace First Occurrence Of a String in python
  • Converting Python Strings to Datetime Objects with Timezone
  • Fixing the 'NoneType object is not iterable' Error in Python
  • Scope rules in C Programming
  • Find The Most Frequent Element in an Array
  • Program to find sum of n natural numbers in C++ [3 Methods]
  • Finding the Maximum and Minimum Elements of an Array using C++
  • The Difference Between int main( ), void main( ) and int main (void)
  • Convering a string into upper or lower case in C++
  • Exceptions in C++
  • How to Improve Technical Skills in Programming
  • Next smaller element to the right
  • Next Smaller Element to Left in an array
  • Next greater to left
  • Next Larger Element
  • Check for subtree in a Binary Tree

How To Fix Unbound Local Errors In Python

Rahul Kumar Yadav

The beginner users of python may get confused when they see an Unbound Local Error problem in Python. To save them from this headache we have provided the cause, and the fixes of this error, which often occurs while coding in Python.

How UnboundLocalError: local variable referenced before assignment occurs

UnboundLocalError: local variable referenced before assignment , error occurs when we are trying to reference the variable inside a function before assigning any value to it.

This error occurs only when the local variable which is in focus is being assigned some value in the function, and we have referenced it before the assignment operation.

Let us take the help of the code to see what I am trying to say:-

The above example will show an error in line 3, where it says UnboundLocalError: local_variable 'string' referenced before assignment .

The above error occurs because there is both assignment and reference of the variable string, and thus, program creates a local variable named as string for the function example, but it is referenced before any value has been assigned(in the line 3, as we are trying to use the value of string to update the value of string) and since, till then there is no value for local variable string in the function, it shows unbound local error.

Had the code been, as given below:-

It would have simply displayed the output:-

As in this case, there is no assignment of the value to the string variable, and thus, no local variable string is created, and thus, it uses the value in the global scope to display.

The problem of UnboundLocalError occurs only when there is an assignment operation of the variable having the same name as outside the function and inside the function, and the variable is referenced before the assignment operation has taken place.

How to Fix UnboundLocalError error

Only way to avoid this error is to assign the variable before referencing it, or to modify it inside the function with a different name and then return that modified value and assign it to the variable outside the function.

Various Ways of Fixing the Above Error

Sometimes we need to use the value of the variable outside the function, and thus it may require referencing before assignment.

There are some ways by which we can bypass this problem, where we need to reference before assignment.

  • Using global keyword:-

The output of the above code is:-

Using the global keyword we can easily circumvent the problem of no referencing before assignment, as then it would be able to use the global variable for further operations inside the function.

  • We can pass the value of variable outside the function as a parameter to the function:-

Upon passing the value, we will be able to use the variable’s value without declaring it as a global variable, as sometimes it is beneficial to not expose the value to every function.

  • Sometimes we want to modify the value of global variable without declaring it as a global variable, we can simply use some other variable, and modify it accordingly and then return its value and assign it to variable whose value we wanted to modify, like in the given example:-

The output of the above code will be :-

In the above code, we have modified the variable string without declaring it as a global variable, by returning the modified value from the function.

  • If we are using a nested function and we want to assign a value to the local variables from the outer function, then we can use the “nonlocal” keyword to access that variable inside the nested function.

The output of the above function will be:-

We can see in the output that we have modified the string present in the outer_example() by accessing it inside the inner_example() .

We can also use the methods numbered 2 and 3 along with this one to modify the variable present in the outer function from the inner function.

We just saw the reasons behind the occurrence of Unbound Local Error in Python, along with various fixes which we can use in our function to bypass the problem along with getting our task accomplished.

  • C Tutorials
  • Java Tutorials
  • C++ Tutorials
  • SQL Tutorials

How To Fix Unbound Local Errors In Python

w3docs logo

  • 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

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

  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots
  • Monitoring Order Book Imbalances for Trading Signals via cryptofeed
  • Detecting Arbitrage Opportunities Across Exchanges with cryptofeed

The Research Scientist Pod

Python UnboundLocalError: local variable referenced before assignment

by Suf | Programming , Python , Tips

If you try to reference a local variable before assigning a value to it within the body of a function, you will encounter the UnboundLocalError: local variable referenced before assignment.

The preferable way to solve this error is to pass parameters to your function, for example:

Alternatively, you can declare the variable as global to access it while inside a function. For example,

This tutorial will go through the error in detail and how to solve it with code examples .

Table of contents

What is scope in python, unboundlocalerror: local variable referenced before assignment, solution #1: passing parameters to the function, solution #2: use global keyword, solution #1: include else statement, solution #2: use global keyword.

Scope refers to a variable being only available inside the region where it was created. A variable created inside a function belongs to the local scope of that function, and we can only use that variable inside that function.

A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available within any scope, global and local.

UnboundLocalError occurs when we try to modify a variable defined as local before creating it. If we only need to read a variable within a function, we can do so without using the global keyword. Consider the following example that demonstrates a variable var created with global scope and accessed from test_func :

If we try to assign a value to var within test_func , the Python interpreter will raise the UnboundLocalError:

This error occurs because when we make an assignment to a variable in a scope, that variable becomes local to that scope and overrides any variable with the same name in the global or outer scope.

var +=1 is similar to var = var + 1 , therefore the Python interpreter should first read var , perform the addition and assign the value back to var .

var is a variable local to test_func , so the variable is read or referenced before we have assigned it. As a result, the Python interpreter raises the UnboundLocalError.

Example #1: Accessing a Local Variable

Let’s look at an example where we define a global variable number. We will use the increment_func to increase the numerical value of number by 1.

Let’s run the code to see what happens:

The error occurs because we tried to read a local variable before assigning a value to it.

We can solve this error by passing a parameter to increment_func . This solution is the preferred approach. Typically Python developers avoid declaring global variables unless they are necessary. Let’s look at the revised code:

We have assigned a value to number and passed it to the increment_func , which will resolve the UnboundLocalError. Let’s run the code to see the result:

We successfully printed the value to the console.

We also can solve this error by using the global keyword. The global statement tells the Python interpreter that inside increment_func , the variable number is a global variable even if we assign to it in increment_func . Let’s look at the revised code:

Let’s run the code to see the result:

Example #2: Function with if-elif statements

Let’s look at an example where we collect a score from a player of a game to rank their level of expertise. The variable we will use is called score and the calculate_level function takes in score as a parameter and returns a string containing the player’s level .

In the above code, we have a series of if-elif statements for assigning a string to the level variable. Let’s run the code to see what happens:

The error occurs because we input a score equal to 40 . The conditional statements in the function do not account for a value below 55 , therefore when we call the calculate_level function, Python will attempt to return level without any value assigned to it.

We can solve this error by completing the set of conditions with an else statement. The else statement will provide an assignment to level for all scores lower than 55 . Let’s look at the revised code:

In the above code, all scores below 55 are given the beginner level. Let’s run the code to see what happens:

We can also create a global variable level and then use the global keyword inside calculate_level . Using the global keyword will ensure that the variable is available in the local scope of the calculate_level function. Let’s look at the revised code.

In the above code, we put the global statement inside the function and at the beginning. Note that the “default” value of level is beginner and we do not include the else statement in the function. Let’s run the code to see the result:

Congratulations on reading to the end of this tutorial! The UnboundLocalError: local variable referenced before assignment occurs when you try to reference a local variable before assigning a value to it. Preferably, you can solve this error by passing parameters to your function. Alternatively, you can use the global keyword.

If you have if-elif statements in your code where you assign a value to a local variable and do not account for all outcomes, you may encounter this error. In which case, you must include an else statement to account for the missing outcome.

For further reading on Python code blocks and structure, go to the article: How to Solve Python IndentationError: unindent does not match any outer indentation level .

Go to the  online courses page on Python  to learn more about Python for data science and machine learning.

Have fun and happy researching!

Profile Picture

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

  • Suf https://researchdatapod.com/author/soofyserial/ How to Solve Python TypeError: cannot unpack non-iterable bool object
  • Suf https://researchdatapod.com/author/soofyserial/ How to Solve Python NameError: name 'time' is not defined
  • Suf https://researchdatapod.com/author/soofyserial/ How to Solve JavaScript: Uncaught SyntaxError Unexpected end of input
  • Suf https://researchdatapod.com/author/soofyserial/ How to Solve Python IndexError: too many indices for array

Buy Me a Coffee ✨

IMAGES

  1. Python 中 UnboundLocalError: Local variable referenced before assignment 错误_迹忆客

    unboundlocalerror local variable 'job_id' referenced before assignment

  2. 【已解决】Bug9. UnboundLocalError: local variable 'A' referenced before assignment

    unboundlocalerror local variable 'job_id' referenced before assignment

  3. python

    unboundlocalerror local variable 'job_id' referenced before assignment

  4. UnboundLocalError: local variable referenced before assignment

    unboundlocalerror local variable 'job_id' referenced before assignment

  5. UnboundLocalError: local variable 'article_list' referenced before assignment · Issue #1 · Dao

    unboundlocalerror local variable 'job_id' referenced before assignment

  6. UnboundLocalError: local variable 'points' referenced before assignment · Issue #148 · tryolabs

    unboundlocalerror local variable 'job_id' referenced before assignment

COMMENTS

  1. How can I fix "UnboundLocalError: local variable referenced ...

    This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an ...

  2. How to Fix - UnboundLocalError: Local variable Referenced ...

    Mar 29, 2024 · Hangup (SIGHUP) Traceback (most recent call last): File "Solution.py", line 7, in <module> example_function() File "Solution.py", line 4, in example_function x += 1 # Trying to modify global variable 'x' without declaring it as global UnboundLocalError: local variable 'x' referenced before assignment Solution for Local variable Referenced ...

  3. [SOLVED] Local Variable Referenced Before Assignment

    Apr 13, 2022 · Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the concept of variable declarations. Python does not have the concept of variable declarations.

  4. How to fix UnboundLocalError: local variable 'x' referenced ...

    May 26, 2023 · 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.

  5. Local variable referenced before assignment in Python

    Apr 8, 2024 · # 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.

  6. Top 2 Methods to Solve the 'Local Variable Referenced Before

    Nov 6, 2024 · 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 ...

  7. How To Fix Unbound Local Errors In Python | StudyMite

    Learn how to fix and prevent unbound local errors in your Python code. This comprehensive guide will provide you with the necessary tools to troubleshoot and debug your code, ensuring that your programs run smoothly and without any errors. From understanding the root cause of unbound local errors to implementing best practices for variable assignment, this guide has you covered.

  8. Python 3: UnboundLocalError: local variable referenced before ...

    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. def example (): x = 5 print (x) example()

  9. UnboundLocalError: Local Variable ‘x’ Accessed ...">Fixing Python UnboundLocalError: Local Variable ‘x’ Accessed ...

    Dec 31, 2023 · 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. 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. Method 3: Using Nonlocal Variables

  10. UnboundLocalError: local variable referenced before ...">Python UnboundLocalError: local variable referenced before ...

    What is Scope in Python? Scope refers to a variable being only available inside the region where it was created. A variable created inside a function belongs to the local scope of that function, and we can only use that variable inside that function.