• 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

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?

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 'radius' referenced before assignment on line 11

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

Decode Python

Python Tutorials & Tips

Fixing ‘UnboundLocalError’ in Python: A Simple Guide with Code Samples

Python is a popular programming language that is widely used for developing various applications. However, like any other programming language, it is not free from errors. One of the common errors that Python developers encounter is the ‘UnboundLocalError’. This error occurs when a local variable is referenced before it is assigned a value. In this article, we will discuss in detail what ‘UnboundLocalError’ is, why it occurs, and how to fix it.

When a variable is defined inside a function, it is considered a local variable. If the function tries to access this variable before it is assigned a value, it results in an ‘UnboundLocalError’. This error can be frustrating for developers, especially when they are working on a large project. However, it is not difficult to fix this error. One of the ways to fix it is by using the ‘global’ keyword to declare the variable as a global variable.

In conclusion, understanding ‘UnboundLocalError’ in Python is crucial for developers who want to avoid errors in their code. By following best practices and using the right techniques, developers can easily fix this error and ensure that their code runs smoothly. In the next section, we will explore in detail how to fix ‘UnboundLocalError’ using code examples.

Understanding UnboundLocalError

UnboundLocalError is a common error in Python that occurs when a local variable is referenced before it has been assigned a value. This error can be confusing for beginners because it is not always clear why it occurs or how to fix it. In this section, we will explore what UnboundLocalError is, why it occurs, and how to identify it.

What is UnboundLocalError?

UnboundLocalError is an exception that occurs when a local variable is referenced before it has been assigned a value. In Python, variables can have either a local or global scope. Local variables are defined within a function and are only accessible within that function. Global variables, on the other hand, are defined outside of a function and can be accessed by any function within the module.

Why Does UnboundLocalError Occur?

UnboundLocalError occurs when a local variable is referenced before it has been assigned a value. This can happen if the variable is defined within a function but is not assigned a value before it is referenced. It can also happen if the variable is defined as a global variable but is not explicitly declared as such using the global statement.

How to Identify UnboundLocalError

UnboundLocalError can be identified by the traceback message that is generated when the error occurs. The traceback message will indicate the line number where the error occurred and provide information about the variable that caused the error.

To fix UnboundLocalError, you need to ensure that all local variables are assigned a value before they are referenced. You can also use the global statement to explicitly declare a variable as a global variable, allowing it to be accessed by any function within the module.

In conclusion, UnboundLocalError is a common error in Python that occurs when a local variable is referenced before it has been assigned a value. To fix this error, you need to ensure that all local variables are assigned a value before they are referenced and use the global statement to declare global variables. By understanding UnboundLocalError and how to fix it, you can write more robust and error-free Python code.

Fixing UnboundLocalError

If you are a Python developer, you may have encountered the UnboundLocalError error while working with local variables or functions. This error occurs when a local variable is referenced before it is assigned a value within a function. In this section, we will discuss how to fix UnboundLocalError in Python.

Solutions for UnboundLocalError

There are several ways to fix UnboundLocalError in Python. One solution is to explicitly declare the variable as global using the global keyword. This will make the variable a global variable instead of a local variable. Here is an example:

In this example, we declared num as a global variable inside the test() function using the global keyword. This allowed us to access and modify the value of num inside the function without raising an UnboundLocalError .

Another solution is to use the int() function to initialize the variable with a value of 0. This will ensure that the variable has a value before it is referenced. Here is an example:

In this example, we used the int() function to initialize num with a value of 0. This prevented the UnboundLocalError from being raised when we referenced num before assigning it a value.

How to Avoid UnboundLocalError

To avoid UnboundLocalError , it is important to understand the concept of local scope and local names in Python. Local scope refers to the area of a program where a variable is defined and can be accessed. Local names refer to the variables defined within a function.

To prevent UnboundLocalError , you should always make sure to assign a value to a local variable before referencing it within a function. You should also avoid using the same name for both global and local variables, as this can cause confusion and lead to errors.

Another way to avoid UnboundLocalError is to use lexical scoping. This means defining a function within another function, which allows the inner function to access the variables of the outer function. This can help prevent UnboundLocalError by ensuring that all variables are defined and assigned a value before they are referenced.

In conclusion, UnboundLocalError is a common error in Python that can be fixed by explicitly declaring variables as global or initializing them with a value using the int() function. To avoid UnboundLocalError , it is important to understand the concept of local scope and local names, and to assign values to local variables before referencing them within a function.

In conclusion, understanding the ‘UnboundLocalError’ in Python is essential for any programmer. This error occurs when a local variable is referenced before it has been assigned a value within a function. It can be frustrating to deal with, but fortunately, there are several ways to fix it.

One common solution is to use the global keyword to declare the variable as global within the function. This allows the function to access the variable outside of its scope. Another solution is to use default arguments in the function definition to initialize the variable with a default value.

It is important to note that this error is a runtime error and can only be detected when the code is executed. Therefore, it is crucial to test your code thoroughly to catch any ‘UnboundLocalError’ before deploying it.

Python is a versatile programming language that is widely used in various fields. Understanding the ‘UnboundLocalError’ and how to fix it is a crucial aspect of programming in Python. By following the tips and tricks outlined in this article, you can avoid this error and write efficient and effective code.

In summary, this guide has covered the basics of the ‘UnboundLocalError’ in Python, including its causes and solutions. We have seen how to use the global keyword and default arguments to fix this error. Hopefully, this article has been helpful in your programming journey, and you can now write better code in Python.

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

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

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 SyntaxError: can’t assign to function call
  • Suf https://researchdatapod.com/author/soofyserial/ How to Solve Python NameError: name 'datetime' is not defined
  • Suf https://researchdatapod.com/author/soofyserial/ How to Solve Python Modulenotfounderror: no module named 'bs4'
  • Suf https://researchdatapod.com/author/soofyserial/ What is the Ternary Operator in Python?

Buy Me a Coffee

IMAGES

  1. "Fixing UnboundLocalError: Local Variable Referenced Before Assignment"

    unboundlocalerror local variable 'radius' referenced before assignment on line 11

  2. UnboundLocalError: local variable referenced before assignment

    unboundlocalerror local variable 'radius' referenced before assignment on line 11

  3. GIS: UnboundLocalError: local variable referenced before assignment

    unboundlocalerror local variable 'radius' referenced before assignment on line 11

  4. UnboundLocalError: Local Variable Referenced Before Assignment

    unboundlocalerror local variable 'radius' referenced before assignment on line 11

  5. UnboundLocalError: local variable 'd' referenced before assignment

    unboundlocalerror local variable 'radius' referenced before assignment on line 11

  6. [Solved] UnBoundLocalError: local variable referenced

    unboundlocalerror local variable 'radius' referenced before assignment on line 11

VIDEO

  1. UBUNTU FIX: UnboundLocalError: local variable 'version' referenced before assignment

  2. Doctor DESTROYS Gender Ideology In 5 Minutes

  3. Returning Address of local variable using pointer (misconception)

  4. Creating Helical Sweep feature Variable Radius using SolidWorks

  5. 笛声缘:笛子一首《歌唱祖国》气势恢宏,吹出满满的正能量!

  6. Live Webinar on Preparation before assignment, data management & video editing

COMMENTS

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

    The following code gives the error UnboundLocalError: local variable 'Var1' referenced before assignment: Var1 = 1 Var2 = 0 def function(): if Var2 == 0 and Var1 > 0: print("Result 1") elif Var2 == 1 and Var1 > 0: print("Result 2") elif Var1 < 1: print("Result 3") Var1 -= 1 function()

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

    Solution for Local variable Referenced Before Assignment in Python. Below, are the approaches to solve “Local variable Referenced Before Assignment”. Global Variable Modification; Nested Function Variable Access; Global Variable Modification

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

    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.

  4. UnboundLocalError: cannot access local variable 'X' where it ...

    The Python "UnboundLocalError: cannot access local variable 'X' where it is not associated with a value" occurs for multiple reasons: Referencing a local variable before assigning a value to it in a function.

  5. 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. Fixing ‘UnboundLocalError’ in Python: A Simple Guide with ...

    To fix UnboundLocalError, you need to ensure that all local variables are assigned a value before they are referenced. You can also use the global statement to explicitly declare a variable as a global variable, allowing it to be accessed by any function within the module.

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

    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.

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

    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.

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

    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.

  10. UnboundLocalError: local variable 'x' referenced before ...">UnboundLocalError: local variable 'x' referenced before ...

    Traceback (most recent call last): File "identify_northsouth_point.py", line 22, in <module> findPoints(geometry, results) File "identify_northsouth_point.py", line 8, in findPoints results['north'] = (x,y) UnboundLocalError: local variable 'x' referenced before assignment