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

by Nathan Sebhastian

Posted on May 26, 2023

Reading time: 2 minutes

python nested function 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: Feb 17, 2023 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

Local variable referenced before assignment in Python

The “local variable referenced before assignment” error occurs in Python when you try to use a local variable before it has been assigned a value.

This error typically arises in situations where you declare a variable within a function but then try to access or modify it before actually assigning a value to it.

Here’s an example to illustrate this error:

In this example, you would encounter the “local variable ‘x’ referenced before assignment” error because you’re trying to print the value of x before it has been assigned a value. To fix this, you should assign a value to x before attempting to access it:

In the corrected version, the local variable x is assigned a value before it’s used, preventing the error.

Keep in mind that Python treats variables inside functions as local unless explicitly stated otherwise using the global keyword (for global variables) or the nonlocal keyword (for variables in nested functions).

If you encounter this error and you’re sure that the variable should have been assigned a value before its use, double-check your code for any logical errors or typos that might be causing the variable to not be assigned properly.

Using the global keyword

If you have a global variable named letter and you try to modify it inside a function without declaring it as global, you will get error.

This is because Python assumes that any variable that is assigned a value inside a function is a local variable, unless you explicitly tell it otherwise.

To fix this error, you can use the global keyword to indicate that you want to use the global variable:

Using nonlocal keyword

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. It allows you to modify the value of a non-local variable in the outer scope.

For example, if you have a function outer that defines a variable x , and another function inner inside outer that tries to change the value of x , you need to use the nonlocal keyword to tell Python that you are referring to the x defined in outer , not a new local variable in inner .

Here is an example of how to use the nonlocal keyword:

If you don’t use the nonlocal keyword, Python will create a new local variable x in inner , and the value of x in outer will not be changed:

python nested function referenced before assignment

Explore your training options in 10 minutes Get Started

  • Graduate Stories
  • Partner Spotlights
  • Bootcamp Prep
  • Bootcamp Admissions
  • University Bootcamps
  • Coding Tools
  • Software Engineering
  • Web Development
  • Data Science
  • Tech Guides
  • Tech Resources
  • Career Advice
  • Online Learning
  • Internships
  • Apprenticeships
  • Tech Salaries
  • Associate Degree
  • Bachelor's Degree
  • Master's Degree
  • University Admissions
  • Best Schools
  • Certifications
  • Bootcamp Financing
  • Higher Ed Financing
  • Scholarships
  • Financial Aid
  • Best Coding Bootcamps
  • Best Online Bootcamps
  • Best Web Design Bootcamps
  • Best Data Science Bootcamps
  • Best Technology Sales Bootcamps
  • Best Data Analytics Bootcamps
  • Best Cybersecurity Bootcamps
  • Best Digital Marketing Bootcamps
  • Los Angeles
  • San Francisco
  • Browse All Locations
  • Digital Marketing
  • Machine Learning
  • See All Subjects
  • Bootcamps 101
  • Full-Stack Development
  • Career Changes
  • View all Career Discussions
  • Mobile App Development
  • Cybersecurity
  • Product Management
  • UX/UI Design
  • What is a Coding Bootcamp?
  • Are Coding Bootcamps Worth It?
  • How to Choose a Coding Bootcamp
  • Best Online Coding Bootcamps and Courses
  • Best Free Bootcamps and Coding Training
  • Coding Bootcamp vs. Community College
  • Coding Bootcamp vs. Self-Learning
  • Bootcamps vs. Certifications: Compared
  • What Is a Coding Bootcamp Job Guarantee?
  • How to Pay for Coding Bootcamp
  • Ultimate Guide to Coding Bootcamp Loans
  • Best Coding Bootcamp Scholarships and Grants
  • Education Stipends for Coding Bootcamps
  • Get Your Coding Bootcamp Sponsored by Your Employer
  • GI Bill and Coding Bootcamps
  • Tech Intevriews
  • Our Enterprise Solution
  • Connect With Us
  • Publication
  • Reskill America
  • Partner With Us

Career Karma

  • Resource Center
  • Bachelor’s Degree
  • Master’s Degree

Python local variable referenced before assignment Solution

When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. This error is raised when you try to use a variable before it has been assigned in the local context .

In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you understand how you can solve it.

Find your bootcamp match

What is unboundlocalerror: local variable referenced before assignment.

Trying to assign a value to a variable that does not have local scope can result in this error:

Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function , that variable is local. This is because it is assumed that when you define a variable inside a function you only need to access it inside that function.

There are two variable scopes in Python: local and global. Global variables are accessible throughout an entire program; local variables are only accessible within the function in which they are originally defined.

Let’s take a look at how to solve this error.

An Example Scenario

We’re going to write a program that calculates the grade a student has earned in class.

We start by declaring two variables:

These variables store the numerical and letter grades a student has earned, respectively. By default, the value of “letter” is “F”. Next, we write a function that calculates a student’s letter grade based on their numerical grade using an “if” statement :

Finally, we call our function:

This line of code prints out the value returned by the calculate_grade() function to the console. We pass through one parameter into our function: numerical. This is the numerical value of the grade a student has earned.

Let’s run our code and see what happens:

An error has been raised.

The Solution

Our code returns an error because we reference “letter” before we assign it.

We have set the value of “numerical” to 42. Our if statement does not set a value for any grade over 50. This means that when we call our calculate_grade() function, our return statement does not know the value to which we are referring.

We do define “letter” at the start of our program. However, we define it in the global context. Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.

We solve this problem in two ways. First, we can add an else statement to our code. This ensures we declare “letter” before we try to return it:

Let’s try to run our code again:

Our code successfully prints out the student’s grade.

If you are using an “if” statement where you declare a variable, you should make sure there is an “else” statement in place. This will make sure that even if none of your if statements evaluate to True, you can still set a value for the variable with which you are going to work.

Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our calculate_grade() function. However, this approach is likely to lead to more confusing code and other issues. In general, variables should not be declared using “global” unless absolutely necessary . Your first, and main, port of call should always be to make sure that a variable is correctly defined.

In the example above, for instance, we did not check that the variable “letter” was defined in all use cases.

That’s it! We have fixed the local variable error in our code.

The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.

Now you’re ready to solve UnboundLocalError Python errors like a professional developer !

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .

What's Next?

icon_10

Get matched with top bootcamps

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

James Gallagher

Leave a Reply Cancel reply

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

Apply to top tech training programs in one click

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!

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Tumblr (Opens in new window)

How to Solve Error - Local Variable Referenced Before Assignment in Python

  • Python How-To's
  • How to Solve Error - Local Variable …

Check the Variable Scope to Fix the local variable referenced before assignment Error in Python

Initialize the variable before use to fix the local variable referenced before assignment error in python, use conditional assignment to fix the local variable referenced before assignment error in python.

How to Solve Error - Local Variable Referenced Before Assignment in Python

This article delves into various strategies to resolve the common local variable referenced before assignment error. By exploring methods such as checking variable scope, initializing variables before use, conditional assignments, and more, we aim to equip both novice and seasoned programmers with practical solutions.

Each method is dissected with examples, demonstrating how subtle changes in code can prevent this frequent error, enhancing the robustness and readability of your Python projects.

The local variable referenced before assignment occurs when some variable is referenced before assignment within a function’s body. The error usually occurs when the code is trying to access the global variable.

The primary purpose of managing variable scope is to ensure that variables are accessible where they are needed while maintaining code modularity and preventing unexpected modifications to global variables.

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

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

In this example, my_var is a global variable. Inside update_var , we attempt to modify it without declaring its scope, leading to the Local Variable Referenced Before Assignment error.

We need to declare the my_var variable as global using the global keyword to resolve this error. The below example code demonstrates how the error can be resolved using the global keyword in the above code scenario.

In the corrected code, we use the global keyword to inform Python that my_var references the global variable.

When we first print my_var , it displays the original value from the global scope.

After assigning a new value to my_var , it updates the global variable, not a local one. This way, we effectively tell Python the scope of our variable, thus avoiding any conflicts between local and global variables with the same name.

python local variable referenced before assignment - output 1

Ensure that the variable is initialized with some value before using it. This can be done by assigning a default value to the variable at the beginning of the function or code block.

The main purpose of initializing variables before use is to ensure that they have a defined state before any operations are performed on them. This practice is not only crucial for avoiding the aforementioned error but also promotes writing clear and predictable code, which is essential in both simple scripts and complex applications.

In this example, the variable total is used in the function calculate_total without prior initialization, leading to the Local Variable Referenced Before Assignment error. The below example code demonstrates how the error can be resolved in the above code scenario.

In our corrected code, we initialize the variable total with 0 before using it in the loop. This ensures that when we start adding item values to total , it already has a defined state (in this case, 0).

This initialization is crucial because it provides a starting point for accumulation within the loop. Without this step, Python does not know the initial state of total , leading to the error.

python local variable referenced before assignment - output 2

Conditional assignment allows variables to be assigned values based on certain conditions or logical expressions. This method is particularly useful when a variable’s value depends on certain prerequisites or states, ensuring that a variable is always initialized before it’s used, thereby avoiding the common error.

In this example, message is only assigned within the if and elif blocks. If neither condition is met (as with guest ), the variable message remains uninitialized, leading to the Local Variable Referenced Before Assignment error when trying to print it.

The below example code demonstrates how the error can be resolved in the above code scenario.

In the revised code, we’ve included an else statement as part of our conditional logic. This guarantees that no matter what value user_type holds, the variable message will be assigned some value before it is used in the print function.

This conditional assignment ensures that the message is always initialized, thereby eliminating the possibility of encountering the Local Variable Referenced Before Assignment error.

python local variable referenced before assignment - output 3

Throughout this article, we have explored multiple approaches to address the Local Variable Referenced Before Assignment error in Python. From the nuances of variable scope to the effectiveness of initializations and conditional assignments, these strategies are instrumental in developing error-free code.

The key takeaway is the importance of understanding variable scope and initialization in Python. By applying these methods appropriately, programmers can not only resolve this specific error but also enhance the overall quality and maintainability of their code, making their programming journey smoother and more rewarding.

[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

Fix "local variable referenced before assignment" in Python

python nested function referenced before assignment

Introduction

If you're a Python developer, you've probably come across a variety of errors, like the "local variable referenced before assignment" error. This error can be a bit puzzling, especially for beginners and when it involves local/global variables.

Today, we'll explain this error, understand why it occurs, and see how you can fix it.

The "local variable referenced before assignment" Error

The "local variable referenced before assignment" error in Python is a common error that occurs when a local variable is referenced before it has been assigned a value. This error is a type of UnboundLocalError , which is raised when a local variable is referenced before it has been assigned in the local scope.

Here's a simple example:

Running this code will throw the "local variable 'x' referenced before assignment" error. This is because the variable x is referenced in the print(x) statement before it is assigned a value in the local scope of the foo function.

Even more confusing is when it involves global variables. For example, the following code also produces the error:

But wait, why does this also produce the error? Isn't x assigned before it's used in the say_hello function? The problem here is that x is a global variable when assigned "Hello ". However, in the say_hello function, it's a different local variable, which has not yet been assigned.

We'll see later in this Byte how you can fix these cases as well.

Fixing the Error: Initialization

One way to fix this error is to initialize the variable before using it. This ensures that the variable exists in the local scope before it is referenced.

Let's correct the error from our first example:

In this revised code, we initialize x with a value of 1 before printing it. Now, when you run the function, it will print 1 without any errors.

Fixing the Error: Global Keyword

Another way to fix this error, depending on your specific scenario, is by using the global keyword. This is especially useful when you want to use a global variable inside a function.

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

Here's how:

In this snippet, we declare x as a global variable inside the function foo . This tells Python to look for x in the global scope, not the local one . Now, when you run the function, it will increment the global x by 1 and print 1 .

Similar Error: NameError

An error that's similar to the "local variable referenced before assignment" error is the NameError . This is raised when you try to use a variable or a function name that has not been defined yet.

Running this code will result in a NameError :

In this case, we're trying to print the value of y , but y has not been defined anywhere in the code. Hence, Python raises a NameError . This is similar in that we are trying to use an uninitialized/undefined variable, but the main difference is that we didn't try to initialize y anywhere else in our code.

Variable Scope in Python

Understanding the concept of variable scope can help avoid many common errors in Python, including the main error of interest in this Byte. But what exactly is variable scope?

In Python, variables have two types of scope - global and local. A variable declared inside a function is known as a local variable, while a variable declared outside a function is a global variable.

Consider this example:

In this code, x is a global variable, and y is a local variable. x can be accessed anywhere in the code, but y can only be accessed within my_function . Confusion surrounding this is one of the most common causes for the "variable referenced before assignment" error.

In this Byte, we've taken a look at the "local variable referenced before assignment" error and another similar error, NameError . We also delved into the concept of variable scope in Python, which is an important concept to understand to avoid these errors. If you're seeing one of these errors, check the scope of your variables and make sure they're being assigned before they're being used.

python nested function referenced before assignment

Building Your First Convolutional Neural Network With Keras

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup

© 2013- 2024 Stack Abuse. All rights reserved.

Can a nested function assign to variables from the parent function

Examples and workarounds in python.

While working on a new feature for Pelican I've put myself in a situation where I have two functions, one nested inside the other and I want the nested function to assign to variable from the parent function. Turns out this isn't so easy in Python!

The example above is a recursive Hello World . Notice the i += 1 line! This line causes i to be considered local to do_print() and the result is that we get the following failure on Python 2.7:

We can workaround by using a global variable like so:

However I prefer not to expose internal state outside the hello() function. Only if there was a keyword similar to global . In Python 3 there is nonlocal !

nonlocal is nice but it doesn't exist in Python 2! The workaround is to not assign state to the variable itself, but instead use a mutable container. That is instead of a scalar use a list or a dictionary like so:

Thanks for reading and happy coding!

tags: Python , fedora.planet

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Python Program That Prints Out the Decimal Equivalents of 1/2, 1/3, 1/4, . . . ,1/10
  • How to Convert PIL Image into pygame surface image?
  • Python program to print the binary value of the numbers from 1 to N
  • Python Program for Sum the digits of a given number
  • Python program to print number of bits to store an integer and also the number in Binary format
  • Python program to get all pairwise combinations from a list
  • Python program to repeat M characters of a string N times
  • How to format a string using a dictionary in Python
  • Python program to convert binary to ASCII
  • Python program to convert unix timestamp string to readable date
  • Python program to print an array of bytes representing an integer
  • Python Program to Multiply Two Binary Numbers
  • Python Program to Find Sum of First and Last Digit
  • Python Program to Sort Words in Alphabetical Order
  • Python program to convert integer to roman
  • Python - Lambda Function to Check if value is in a List
  • Python - Get first element from a List of tuples
  • Get Your System Information - Using Python Script
  • Python - Get the object with the max attribute value in a list of objects

UnboundLocalError Local variable Referenced Before Assignment in Python

Handling errors is an integral part of writing robust and reliable Python code. One common stumbling block that developers often encounter is the “UnboundLocalError” raised within a try-except block. This error can be perplexing for those unfamiliar with its nuances but fear not – in this article, we will delve into the intricacies of the UnboundLocalError and provide a comprehensive guide on how to effectively use try-except statements to resolve it.

What is UnboundLocalError Local variable Referenced Before Assignment in Python?

The UnboundLocalError occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.

Why does UnboundLocalError: Local variable Referenced Before Assignment Occur?

below, are the reasons of occurring “Unboundlocalerror: Try Except Statements” in Python :

Variable Assignment Inside Try Block

Reassigning a global variable inside except block.

  • Accessing a Variable Defined Inside an If Block

In the below code, example_function attempts to execute some_operation within a try-except block. If an exception occurs, it prints an error message. However, if no exception occurs, it prints the value of the variable result outside the try block, leading to an UnboundLocalError since result might not be defined if an exception was caught.

In below code , modify_global function attempts to increment the global variable global_var within a try block, but it raises an UnboundLocalError. This error occurs because the function treats global_var as a local variable due to the assignment operation within the try block.

Solution for UnboundLocalError Local variable Referenced Before Assignment

Below, are the approaches to solve “Unboundlocalerror: Try Except Statements”.

Initialize Variables Outside the Try Block

Avoid reassignment of global variables.

In modification to the example_function is correct. Initializing the variable result before the try block ensures that it exists even if an exception occurs within the try block. This helps prevent UnboundLocalError when trying to access result in the print statement outside the try block.

Below, code calculates a new value ( local_var ) based on the global variable and then prints both the local and global variables separately. It demonstrates that the global variable is accessed directly without being reassigned within the function.

In conclusion , To fix “UnboundLocalError” related to try-except statements, ensure that variables used within the try block are initialized before the try block starts. This can be achieved by declaring the variables with default values or assigning them None outside the try block. Additionally, when modifying global variables within a try block, use the `global` keyword to explicitly declare them.

Please Login to comment...

  • Python Errors
  • WhatsApp To Launch New App Lock Feature
  • Top Design Resources for Icons
  • Node.js 21 is here: What’s new
  • Zoom: World’s Most Innovative Companies of 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

BlogsDope image

Nested function, Scope of variable & closures in Python

submit your article

This post first introduces nested functions and then the different scopes of variables like global variables, local variables in functions etc., and finally, closures using the nested function in Python.

You can learn about Python's function from our Python course and this post .

Nested function

Like nested loops, we can also have nested functions in Python. We simply create a function using def inside another function to nest two functions. For example,

Hello world

This seems quite simple. You can see that we also accessed the variables of the outer function from the inner function. So, let's try to change the variables of the outer function from the inner one.

From the above two examples, you can see that we are able to print the variables of the outer function from the inner one but not able to change it. x=4 created a new variable named 'x' inside the function f2 instead of changing the value of the variable 'x' of the function f1. So before moving on to more discussions about nested functions, let's know about the scope of variables in Python first, i.e., where variables live and from where we can access them.

Scope of variables

The location where we can find a variable and also access it if required is called the scope of a variable. So, let's learn what these scopes are.

Local and Global variables

A variable in a function in Python is a local variable if it is not declared as something else. A local variable can be accessed only locally i.e., a variable defined inside a function is accessible to that function only and can't be used outside the function.

Output Traceback (most recent call last):   File "a.py", line 5, in <module>     print x # will give error NameError: name 'x' is not defined

You can see that the variable 'a' created inside the function is a local variable and is inaccessible outside the function.

Also, we can access from a function the variables which are defined outside that function but can't modify them.

We are able to print the global variable 'a'. Python first looked for a variable named 'a' inside the function and when it was not found, it looked in the global scope and printed the global value of 'a'.

You can see that declaring a = 5 , created a new local variable inside the function instead of changing the existing global variable 'a'. This is because Python assumes that a variable is local if it is not explicitly declared global.

To tell Python that we want to use the global variable inside the function, we need to use the global keyword. An example is given below.

Please note that unlike other languages like C, Python doesn't have any separate scope for loops, if/else, etc. Thus, changing variables inside a loop will change the global variable also.

After understanding global and local variables, let's dive into the scope of variables in nested functions.

Scope of variables in nested function

We already know how to access a global variable form a function.  In this section, we will learn about accessing and changing the variables of an outer function from the inner one. So, first let's try to print a variable of an outer function from the inner one.

You can see that we are able to print the variable of the outer function. This is similar to printing a global variable from a function.

Let's try to change the value of the variable of an outer function.

You can see that we are not able to change the value of the variable of the outer function from the inner one. a=2 created a new local variable of function f2 instead of changing the value of 'a' from the function f1.

There are different ways to change the value of the local variable of the outer function from the inner function. The first way is to use an iterable.

We can also change the value of the variable as shown in the next example.

The third way is to use the nonlocal keyword. Please note that the nonlocal keyword only works with Python3. You can use any of the two ways mentioned above to change the value of the variable in Python2.

We can use the nonlocal keyword to change the value of the variable of the outer function similar to using global keyword to change the value of global variables.

As you are ready with the concepts of scopes of variables, let's learn about closures in Python.

Closure is basically keeping a record of a function with an environment. For example, if we call a function with an argument (foo(1)), then it must keep a record of the environment with that argument to be used later in the program. It will be clear from the examples given below.  

Output 3 102

You can see that the environment created by f1(1) is different from that of f1(100), and both were remembered by Python, thus printing different values for a(2) and b(2). This is what closure is.

So basically, a function (object) that remembers the environment where it was made is a closure.

A closure is also the answer to the question - "What is the use of nested function". But this also gives us another question - "What is the use of closures?"

Classes are more flexible than closures but closures are faster. One can make closures to handle simple cases where making a class is not really necessary.

C++ : Linked lists in C++ (Singly linked list)

Adding outline to text using css, set, toggle and clear a bit in c, 12 creative css and javascript text typing animations, inserting a new node to a linked list in c++, pow() in python, dutch national flag problem - sort 0, 1, 2 in an array, memoryview() in python, next() in python, map() in python, mouse rollover zoom effect on images, important functions in math.h library of c, formatting the print using printf in c, linked list traversal using loop and recursion in c++, calculator using java swing and awt with source code, animate your website elements with css transforms, controlling the outline position with outline-offset, prime numbers using sieve algorithm in c.

article on blogsdope

Please login to view or add comment(s).

python nested function referenced before assignment

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 227 – Statically Nested Scopes

Introduction, specification, backwards compatibility, compatibility of c api, locals() / vars(), import * used in function scope, bare exec in function scope, local shadows global, rebinding names in enclosing scopes, implementation.

This PEP describes the addition of statically nested scoping (lexical scoping) for Python 2.2, and as a source level option for python 2.1. In addition, Python 2.1 will issue warnings about constructs whose meaning may change when this feature is enabled.

The old language definition (2.0 and before) defines exactly three namespaces that are used to resolve names – the local, global, and built-in namespaces. The addition of nested scopes allows resolution of unbound local names in enclosing functions’ namespaces.

The most visible consequence of this change is that lambdas (and other nested functions) can reference variables defined in the surrounding namespace. Currently, lambdas must often use default arguments to explicitly creating bindings in the lambda’s namespace.

This proposal changes the rules for resolving free variables in Python functions. The new name resolution semantics will take effect with Python 2.2. These semantics will also be available in Python 2.1 by adding “from __future__ import nested_scopes” to the top of a module. (See PEP 236 .)

The Python 2.0 definition specifies exactly three namespaces to check for each name – the local namespace, the global namespace, and the builtin namespace. According to this definition, if a function A is defined within a function B, the names bound in B are not visible in A. The proposal changes the rules so that names bound in B are visible in A (unless A contains a name binding that hides the binding in B).

This specification introduces rules for lexical scoping that are common in Algol-like languages. The combination of lexical scoping and existing support for first-class functions is reminiscent of Scheme.

The changed scoping rules address two problems – the limited utility of lambda expressions (and nested functions in general), and the frequent confusion of new users familiar with other languages that support nested lexical scopes, e.g. the inability to define recursive functions except at the module level.

The lambda expression yields an unnamed function that evaluates a single expression. It is often used for callback functions. In the example below (written using the Python 2.0 rules), any name used in the body of the lambda must be explicitly passed as a default argument to the lambda.

This approach is cumbersome, particularly when there are several names used in the body of the lambda. The long list of default arguments obscures the purpose of the code. The proposed solution, in crude terms, implements the default argument approach automatically. The “root=root” argument can be omitted.

The new name resolution semantics will cause some programs to behave differently than they did under Python 2.0. In some cases, programs will fail to compile. In other cases, names that were previously resolved using the global namespace will be resolved using the local namespace of an enclosing function. In Python 2.1, warnings will be issued for all statements that will behave differently.

Python is a statically scoped language with block structure, in the traditional of Algol. A code block or region, such as a module, class definition, or function body, is the basic unit of a program.

Names refer to objects. Names are introduced by name binding operations. Each occurrence of a name in the program text refers to the binding of that name established in the innermost function block containing the use.

The name binding operations are argument declaration, assignment, class and function definition, import statements, for statements, and except clauses. Each name binding occurs within a block defined by a class or function definition or at the module level (the top-level code block).

If a name is bound anywhere within a code block, all uses of the name within the block are treated as references to the current block. (Note: This can lead to errors when a name is used within a block before it is bound.)

If the global statement occurs within a block, all uses of the name specified in the statement refer to the binding of that name in the top-level namespace. Names are resolved in the top-level namespace by searching the global namespace, i.e. the namespace of the module containing the code block, and in the builtin namespace, i.e. the namespace of the __builtin__ module. The global namespace is searched first. If the name is not found there, the builtin namespace is searched. The global statement must precede all uses of the name.

If a name is used within a code block, but it is not bound there and is not declared global, the use is treated as a reference to the nearest enclosing function region. (Note: If a region is contained within a class definition, the name bindings that occur in the class block are not visible to enclosed functions.)

A class definition is an executable statement that may contain uses and definitions of names. These references follow the normal rules for name resolution. The namespace of the class definition becomes the attribute dictionary of the class.

The following operations are name binding operations. If they occur within a block, they introduce new local names in the current block unless there is also a global declaration.

There are several cases where Python statements are illegal when used in conjunction with nested scopes that contain free variables.

If a variable is referenced in an enclosed scope, it is an error to delete the name. The compiler will raise a SyntaxError for ‘del name’.

If the wild card form of import ( import * ) is used in a function and the function contains a nested block with free variables, the compiler will raise a SyntaxError .

If exec is used in a function and the function contains a nested block with free variables, the compiler will raise a SyntaxError unless the exec explicitly specifies the local namespace for the exec. (In other words, “exec obj” would be illegal, but “exec obj in ns” would be legal.)

If a name bound in a function scope is also the name of a module global name or a standard builtin name, and the function contains a nested function scope that references the name, the compiler will issue a warning. The name resolution rules will result in different bindings under Python 2.0 than under Python 2.2. The warning indicates that the program may not run correctly with all versions of Python.

The specified rules allow names defined in a function to be referenced in any nested function defined with that function. The name resolution rules are typical for statically scoped languages, with three primary exceptions:

  • Names in class scope are not accessible.
  • The global statement short-circuits the normal rules.
  • Variables are not declared.

Names in class scope are not accessible. Names are resolved in the innermost enclosing function scope. If a class definition occurs in a chain of nested scopes, the resolution process skips class definitions. This rule prevents odd interactions between class attributes and local variable access. If a name binding operation occurs in a class definition, it creates an attribute on the resulting class object. To access this variable in a method, or in a function nested within a method, an attribute reference must be used, either via self or via the class name.

An alternative would have been to allow name binding in class scope to behave exactly like name binding in function scope. This rule would allow class attributes to be referenced either via attribute reference or simple name. This option was ruled out because it would have been inconsistent with all other forms of class and instance attribute access, which always use attribute references. Code that used simple names would have been obscure.

The global statement short-circuits the normal rules. Under the proposal, the global statement has exactly the same effect that it does for Python 2.0. It is also noteworthy because it allows name binding operations performed in one block to change bindings in another block (the module).

Variables are not declared. If a name binding operation occurs anywhere in a function, then that name is treated as local to the function and all references refer to the local binding. If a reference occurs before the name is bound, a NameError is raised. The only kind of declaration is the global statement, which allows programs to be written using mutable global variables. As a consequence, it is not possible to rebind a name defined in an enclosing scope. An assignment operation can only bind a name in the current scope or in the global scope. The lack of declarations and the inability to rebind names in enclosing scopes are unusual for lexically scoped languages; there is typically a mechanism to create name bindings (e.g. lambda and let in Scheme) and a mechanism to change the bindings (set! in Scheme).

A few examples are included to illustrate the way the rules work.

An example from Tim Peters demonstrates the potential pitfalls of nested scopes in the absence of declarations:

The call to g() will refer to the variable i bound in f() by the for loop. If g() is called before the loop is executed, a NameError will be raised.

There are two kinds of compatibility problems caused by nested scopes. In one case, code that behaved one way in earlier versions behaves differently because of nested scopes. In the other cases, certain constructs interact badly with nested scopes and will trigger SyntaxErrors at compile time.

The following example from Skip Montanaro illustrates the first kind of problem:

Under the Python 2.0 rules, the print statement inside inner() refers to the global variable x and will print 1 if f1() is called. Under the new rules, it refers to the f1() ’s namespace, the nearest enclosing scope with a binding.

The problem occurs only when a global variable and a local variable share the same name and a nested function uses that name to refer to the global variable. This is poor programming practice, because readers will easily confuse the two different variables. One example of this problem was found in the Python standard library during the implementation of nested scopes.

To address this problem, which is unlikely to occur often, the Python 2.1 compiler (when nested scopes are not enabled) issues a warning.

The other compatibility problem is caused by the use of import * and ‘exec’ in a function body, when that function contains a nested scope and the contained scope has free variables. For example:

At compile-time, the compiler cannot tell whether an exec that operates on the local namespace or an import * will introduce name bindings that shadow the global y. Thus, it is not possible to tell whether the reference to y in g() should refer to the global or to a local name in f() .

In discussion of the python-list, people argued for both possible interpretations. On the one hand, some thought that the reference in g() should be bound to a local y if one exists. One problem with this interpretation is that it is impossible for a human reader of the code to determine the binding of y by local inspection. It seems likely to introduce subtle bugs. The other interpretation is to treat exec and import * as dynamic features that do not effect static scoping. Under this interpretation, the exec and import * would introduce local names, but those names would never be visible to nested scopes. In the specific example above, the code would behave exactly as it did in earlier versions of Python.

Since each interpretation is problematic and the exact meaning ambiguous, the compiler raises an exception. The Python 2.1 compiler issues a warning when nested scopes are not enabled.

A brief review of three Python projects (the standard library, Zope, and a beta version of PyXPCOM) found four backwards compatibility issues in approximately 200,000 lines of code. There was one example of case #1 (subtle behavior change) and two examples of import * problems in the standard library.

(The interpretation of the import * and exec restriction that was implemented in Python 2.1a2 was much more restrictive, based on language that in the reference manual that had never been enforced. These restrictions were relaxed following the release.)

The implementation causes several Python C API functions to change, including PyCode_New() . As a result, C extensions may need to be updated to work correctly with Python 2.1.

These functions return a dictionary containing the current scope’s local variables. Modifications to the dictionary do not affect the values of variables. Under the current rules, the use of locals() and globals() allows the program to gain access to all the namespaces in which names are resolved.

An analogous function will not be provided for nested scopes. Under this proposal, it will not be possible to gain dictionary-style access to all visible scopes.

Warnings and Errors

The compiler will issue warnings in Python 2.1 to help identify programs that may not compile or run correctly under future versions of Python. Under Python 2.2 or Python 2.1 if the nested_scopes future statement is used, which are collectively referred to as “future semantics” in this section, the compiler will issue SyntaxErrors in some cases.

The warnings typically apply when a function that contains a nested function that has free variables. For example, if function F contains a function G and G uses the builtin len() , then F is a function that contains a nested function (G) with a free variable (len). The label “free-in-nested” will be used to describe these functions.

The language reference specifies that import * may only occur in a module scope. (Sec. 6.11) The implementation of C Python has supported import * at the function scope.

If import * is used in the body of a free-in-nested function, the compiler will issue a warning. Under future semantics, the compiler will raise a SyntaxError .

The exec statement allows two optional expressions following the keyword “in” that specify the namespaces used for locals and globals. An exec statement that omits both of these namespaces is a bare exec.

If a bare exec is used in the body of a free-in-nested function, the compiler will issue a warning. Under future semantics, the compiler will raise a SyntaxError .

If a free-in-nested function has a binding for a local variable that (1) is used in a nested function and (2) is the same as a global variable, the compiler will issue a warning.

There are technical issues that make it difficult to support rebinding of names in enclosing scopes, but the primary reason that it is not allowed in the current proposal is that Guido is opposed to it. His motivation: it is difficult to support, because it would require a new mechanism that would allow the programmer to specify that an assignment in a block is supposed to rebind the name in an enclosing block; presumably a keyword or special syntax (x := 3) would make this possible. Given that this would encourage the use of local variables to hold state that is better stored in a class instance, it’s not worth adding new syntax to make this possible (in Guido’s opinion).

The proposed rules allow programmers to achieve the effect of rebinding, albeit awkwardly. The name that will be effectively rebound by enclosed functions is bound to a container object. In place of assignment, the program uses modification of the container to achieve the desired effect:

Support for rebinding in nested scopes would make this code clearer. A class that defines deposit() and withdraw() methods and the balance as an instance variable would be clearer still. Since classes seem to achieve the same effect in a more straightforward manner, they are preferred.

The implementation for C Python uses flat closures [1] . Each def or lambda expression that is executed will create a closure if the body of the function or any contained function has free variables. Using flat closures, the creation of closures is somewhat expensive but lookup is cheap.

The implementation adds several new opcodes and two new kinds of names in code objects. A variable can be either a cell variable or a free variable for a particular code object. A cell variable is referenced by containing scopes; as a result, the function where it is defined must allocate separate storage for it on each invocation. A free variable is referenced via a function’s closure.

The choice of free closures was made based on three factors. First, nested functions are presumed to be used infrequently, deeply nested (several levels of nesting) still less frequently. Second, lookup of names in a nested scope should be fast. Third, the use of nested scopes, particularly where a function that access an enclosing scope is returned, should not prevent unreferenced objects from being reclaimed by the garbage collector.

Source: https://github.com/python/peps/blob/main/peps/pep-0227.rst

Last modified: 2023-09-09 17:39:29 GMT

Adventures in Machine Learning

4 ways to fix local variable referenced before assignment error in python, resolving the local variable referenced before assignment error in python.

Python is one of the world’s most popular programming languages due to its simplicity, readability, and versatility. Despite its many advantages, when coding in Python, one may encounter various errors, with the most common being the “local variable referenced before assignment” error.

Even the most experienced Python developers have encountered this error at some point in their programming career. In this article, we will look at four effective strategies for resolving the local variable referenced before assignment error in Python.

Strategy 1: Assigning a Value before Referencing

The first strategy is to assign a value to a variable before referencing it. The error occurs when the variable is referenced before it is assigned a value.

This problem can be avoided by initializing the variable before referencing it. For example, let us consider the snippet below:

“`python

add_numbers():

print(x + y)

add_numbers()

In the snippet above, the variables `x` and `y` are not assigned values before they are referenced in the `print` statement. Therefore, we will get a local variable “referenced before assignment” error.

To resolve this error, we must initialize the variables before referencing them. We can avoid this error by assigning a value to `x` and `y` before they are referenced, as shown below:

Strategy 2: Using the Global Keyword

In Python, variables declared inside a function are considered local variables. Thus, they are separate from other variables declared outside of the function.

If we want to use a variable outside of the function, we must use the global keyword. Using the global keyword tells Python that you want to use the variable that was defined globally, not locally.

For example:

In the code snippet above, the `global` keyword tells Python to use the variable `x` defined outside of the function rather than a local variable named `x`. Thus, Python will output 30.

Strategy 3: Adding Input Parameters for Functions

Another way to avoid the local variable referenced before assignment error is by adding input parameters to functions.

def add_numbers(x, y):

add_numbers(10, 20)

In the code snippet above, `x` and `y` are variables that are passed into the `add_numbers` function as arguments.

This approach allows us to avoid the local variable referenced before assignment error because the variables are being passed into the function as input parameters. Strategy 4: Initializing Variables before Loops or Conditionals

Finally, it’s also a good practice to initialize the variables before loops or conditionals.

If you are defining a variable within a loop, you must initialize it before the loop starts. This way, the variable already exists, and we can update the value inside the loop.

my_list = [1, 2, 3, 4, 5]

for number in my_list:

sum += number

In the code snippet above, the variable `sum` has been initialized with the value of 0 before the loop runs. Thus, we can update and use the variable inside the loop.

In conclusion, the “local variable referenced before assignment” error is a common issue in Python. However, with the strategies discussed in this article, you can avoid the error and write clean Python code.

Remember to initialize your variables, use the global keyword, add input parameters in functions, and initialize variables before loops or conditionals. By following these techniques, your Python code will be error-free and much easier to manage.

In essence, this article has provided four key strategies for resolving the “local variable referenced before assignment” error that is common in Python. These strategies include initializing variables before referencing, using the global keyword, adding input parameters to functions, and initializing variables before loops or conditionals.

These techniques help to ensure clean code that is free from errors. By implementing these strategies, developers can improve their code quality and avoid time-wasting errors that can occur in their work.

Popular Posts

Mastering operating system tasks: a guide to python’s os module, solving sql problems with cross joining: a comprehensive guide, mastering python comparison operators: a comprehensive guide.

  • Terms & Conditions
  • Privacy Policy

Newbie issue; local variable referenced before assignment

Hello everybody!

I have only been working with python for about 4 days now, so i know my skillset is “somewhat” lackluster, but i fail to grasp what im doing wrong here…

I have a raspbery pico running a version of something called circuitpython.

I have 2 files; main.py and myDisplay.py.

some pseudo-code: (big chunks of code is missing to try to keep the “pseudo”-code as short as possible, but i think my error should be here somewhere…)

The error im getting is: Traceback (most recent call last): File “”, line 15, in File “myDisplay.py”, line 61, in doButtons NameError: local variable referenced before assignment

The module error line number corresponds with the function call for the doButtons function The doButtons line number corresponds with the first time i use the BackLight_val variable inside a function.

I have been working with C for the past deckade (Arduino), so this feels like a namespace issue, but my logic dictates that the variable name is already “global” (inside that particular “module” named myDisplay"), since its declared before the function.

Ive been trying to get around this issue with no success, the rest of my program does work fine, but it crashes when i try to use a button to modify the backlight intensity.

The rule is that if you assign to a name in a function, the name is assumed to be local to that function unless you say otherwise with global or nonlocal .

In myDisplay.py, you’re assigning to BackLight_Val at the module level.

Also, in that same module, you’re assigning to BackLight_Val in the function doButtons , but, in doing so, Python is assuming that that name is local to the function. It’s not the same variable as the one that exists at the module level. You have 2 variables called BackLight_Val , one in the function’s namespace and another in the module’s namespace.

The solution is to tell Python that the local one is the same as the global one by adding the line:

in the function.

:smiling_face_with_three_hearts:

The python namespace works quite differently from what im used to (C), so i really appreciate that you took the time to explain it.

Related Topics

Python Scoping Rules – A Simple Illustrated Guide

Introduction to scope in python, ❖ what is name in python.

Everything in Python is an object. Since everything is an object we need to identify and distinguish each type of object from one another and this is what a name does. Name is simply a unique name given to objects in Python so that they can be identified. For example, when a function is defined in a program, it is given a name that is used to identify the function. Another example is a simple variable assignment var = 25 . Here 2 is the object stored in the memory while var is the name given to the object.

❖ What is Scope ?

The scope of a name like a variable, function, object, etc. is the region or part of the program where the name can be accessed directly. In other words, a name is visible and accessible only within its scope.

❖ What is Namespace ?

A namespace is simply a collection of names. It is a container that contains the names mapped to their respective objects. Namespaces are isolated; thus same names within different scopes do not collide.

? The namespace that contains all the built-in names is created by default because of which built-in functions like print() can be accessed from all parts of the program.

In the above example, we can see that the variable is in the global namespace as well as inside the local namespace and does not collide. Now that brings us to a very important discussion on variable scopes and the LEGB rule of scope resolution.

The LEGB Rule And Variable Scopes

Scope Of Variables In Python

LEGB is an abbreviation for Local(L)-Enclosed(E)-Global(G)-Built-In(B) and it is used to define Python Scope resolution. Let’s understand what is scope resolution and how LEGB works.

Disclaimer: The LEGB rules are specific to variable names and not attributes.

❖ Local Scope (L)

When a variable/name is created inside a function, it is only available within the scope of that function and ceases to exist if used outside the function. Thus the variable belongs to the  local scope  of the function. Every time the function is called, a new local scope is created. Local scope is also called function scope .

❖ Enclosing Scope (E)

An enclosing scope occurs when we have nested functions. When the variable is in the scope of the outside function, it means that the variable is in the enclosing scope of the function. Therefore, the variable is visible within the scope of the inner and outer functions. Enclosing Scope is often called non-local scope.

enclosed variable

In the above example, the variable  scope  is inside the enclosing scope of the function  foo()  and available inside the  foo()  as well as  func()  functions.

❖ Global Scope (G)

A global variable is a variable that is declared in a  global scope  and can be used across the entire program; that means it can be accessed inside as well outside the scope of a function. A global name is generally declared outside functions, in the main body of the Python code. In the backend, Python converts the programs main script into the __main__ module which is responsible for the execution of the main program. The namespace of the __main__ module is the global scope.

❖ Built-In Scope (B)

The built-in scope is the widest scope available in python and contains keywords, functions, exceptions, and other attributes that are built into Python. Names in the built-in scope are available all across the python program. It is loaded automatically at the time of executing a Python program/script.

❖ Example Of Scoping Rules In Python

The following diagram provides a pictorial representation of scopes rules in Python:

Understanding UnboundLocalError In Python

UnboundLocalError In Python

When a  variable  is assigned within a function, it is treated as a local variable by default in Python. If a local  variable  is referenced before a value has been assigned/bound to it, an  UnboundLocalError  is raised. In the above example when the variable  'val'  is read by the Python interpreter inside the  func()  function, it assumes that  'val'  is a local variable. However, it soon realizes that the local variable has been referenced before any value has been assigned to it within the function. Thus it throws an  UnboundLocalError .

In other words, we can only access a global variable inside a function but cannot modify it from within the function (unless you force a global or nonlocal assignment using the  global  or  nonlocal   keywords ).

Resolution: To resolve an  UnboundLocalError  when the local variable is reassigned after the first use, you can either use the  global   keyword or the  nonlocal  keyword. The  global  keyword allows you to modify the values of a global variable from within a function’s local scope while the  nonlocal  keyword provides similar functionality in the case of nested functions.

That brings us to a very important topic – global and nonlocal keywords.

The global And nonlocal Keyword In Python

❖ the global keyword.

We already read about the global scope where we learned that every variable that is declared in the main body and outside any function in the Python code is global by default. However, if we have a situation where we need to declare a global variable inside a function as in the problem statement of this article, then the  global keyword  comes to our rescue. We use the  global keyword  inside a function to make a variable global within the local scope. This means that the global keyword allows us to modify and use a variable outside the scope of the function within which it has been defined.

Now let us have a look at the following program to understand the usage of the  global  keyword.

❖ The nonlocal Keyword

The  nonlocal  keyword is useful when we have a nested function, i.e., functions having variables in the enclosing scope. In other words, if you want to change/modify a variable that is in the scope of the enclosing function (outer function), then you can use the  nonlocal  keyword. If we change the value of a  nonlocal  variable the value of the  local  variable also changes.

❖ Global Keyword vs Nonlocal Keyword

Before concluding this article, let us have a look at the key differences between a global and nonlocal variable/keywords.

  • Unlike the global keyword, the nonlocal keyword works only in Python 3 and above .
  • The global keyword can be used with pre-existing global variables or new variables whereas the nonlocal keyword must be defined with a pre-existing variable.

In this article we learned the following:

  • What are names in Python?
  • What are namespaces in Python?
  • What are scopes in Python?
  • The LEGB Scope Resolution Rule in Python.
  • The UnboundLocalError.
  • The Global and Nonlocal Keyword.

Please subscribe and stay tuned for more articles!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES! , consider becoming a Python freelance developer ! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork LinkedIn

IMAGES

  1. Nested Loops in Python: A Complete Guide

    python nested function referenced before assignment

  2. How to use NESTED Functions in Python? (Inner Functions + Closures

    python nested function referenced before assignment

  3. Learn Python Functions with Parameters, Nested Functions, Scope Rules

    python nested function referenced before assignment

  4. Beginners Guide to Python Closures

    python nested function referenced before assignment

  5. Python Nested Functions Tutorial

    python nested function referenced before assignment

  6. How to Create Nested Functions in Python?

    python nested function referenced before assignment

VIDEO

  1. 4.32 Python Nested Function

  2. 15. Python Nested Functions

  3. Nested Functions in Python with Example Programs

  4. Nested Conditions|Assignment-4 Answers|Python|INTENSIVE 2.0| NxtWave|CCBP 4.0 #ccbp#nxtwave

  5. local variable referenced before assignment error in python in hindi

  6. Nested Or Inner Function In Python

COMMENTS

  1. Python nested functions variable scoping

    UnboundLocalError: local variable 'b' referenced before assignment It seems mysterious that the presence of b = 4 might somehow make b disappear on the lines that precede it. But the text David quotes explains why: during static analysis, the interpreter determines that b is assigned to in inner, and that it is therefore a local variable of inner.

  2. python

    I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar. #!/usr/bin/python total def checkTotal(): global total total = 0 See this example:

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

    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.

  4. Local variable referenced before assignment in Python

    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.

  5. Local variable referenced before assignment in Python

    Using nonlocal keyword. The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. It allows you to modify the value of a non-local variable in the outer scope. For example, if you have a function outer that defines a variable x, and another function inner inside outer that tries to change the value of x, you need to ...

  6. Python local variable referenced before assignment Solution

    Trying to assign a value to a variable that does not have local scope can result in this error: UnboundLocalError: local variable referenced before assignment. Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function, that variable is local. This is because it is assumed that when you define a ...

  7. Python UnboundLocalError: local variable referenced before assignment

    UnboundLocalError: local variable referenced before assignment. Example #1: Accessing a Local Variable. Solution #1: Passing Parameters to the Function. Solution #2: Use Global Keyword. Example #2: Function with if-elif statements. Solution #1: Include else statement. Solution #2: Use global keyword. Summary.

  8. Local Variable Referenced Before Assignment in Python

    This tutorial explains the reason and solution of the python error local variable referenced before assignment

  9. [SOLVED] Local Variable Referenced Before Assignment

    A local variable is declared primarily within a Python function. Global variables are in the global scope, outside a function. A local variable is created when the function is called and destroyed when the execution is finished. A Global Variable is created upon execution and exists in memory till the program stops.

  10. Python nested function variable scope

    Python nested function variable scope. ... UnboundLocalError: local variable 'b' referenced before assignment. It seems mysterious that the presence of b = 4 might somehow make b disappear on the lines that precede it. But the text David quotes explains why: during static analysis, the interpreter determines that b is assigned to in inner, ...

  11. python

    The Solution (in python 3) Python 3 has introduced the nonlocal statement, which works much like the global statement, but lets us access variables of the surrounding function (rather than global variables). Simply add nonlocal ctr at the top of the inner function and the problem will go away: def outer(): ctr = 0. def inner():

  12. Fix "local variable referenced before assignment" in Python

    This is because the variable x is referenced in the print(x) statement before it is assigned a value in the local scope of the foo function. Even more confusing is when it involves global variables. For example, the following code also produces the error:

  13. Can a nested function assign to variables from the parent function

    Can a nested function assign to variables from the parent function examples and workarounds in Python ... File "./test.py", line 13, in hello do_print File "./test.py", line 6, in do_print if i >= 5: UnboundLocalError: local variable 'i' referenced before assignment. We can workaround by using a global variable like so:

  14. UnboundLocalError Local variable Referenced Before Assignment in Python

    Python - Lambda Function to Check if value is in a List; Python - Get first element from a List of tuples ... UnboundLocalError: local variable 'result' referenced before assignment Why does UnboundLocalError: Local variable Referenced Before Assignment Occur? ... Python - Maximum value assignment in Nested Dictionary

  15. Nested function, Scope of variable & closures in Python

    Output. 5. We are able to print the global variable 'a'. Python first looked for a variable named 'a' inside the function and when it was not found, it looked in the global scope and printed the global value of 'a'. a = 1 def f1(): a = 5 print (a) #will print 5 print (a) #will print 1 f1() Output. 1.

  16. PEP 227

    Under the Python 2.0 rules, the print statement inside inner() refers to the global variable x and will print 1 if f1() is called. Under the new rules, it refers to the f1() 's namespace, the nearest enclosing scope with a binding.. The problem occurs only when a global variable and a local variable share the same name and a nested function uses that name to refer to the global variable.

  17. 4 Ways to Fix Local Variable Referenced Before Assignment Error in Python

    Resolving the Local Variable Referenced Before Assignment Error in Python. Python is one of the world's most popular programming languages due to its simplicity ...

  18. Newbie issue; local variable referenced before assignment

    MRAB (Matthew Barnett) January 24, 2023, 6:34pm 2. The rule is that if you assign to a name in a function, the name is assumed to be local to that function unless you say otherwise with global or nonlocal. In myDisplay.py, you're assigning to BackLight_Val at the module level. Also, in that same module, you're assigning to BackLight_Val in ...

  19. python 2.7

    The nested functions in your program have their own local namespace/scope different from the outer function that calls them. According to Python documentation If a name is declared global, then all references and assignments go directly to the middle scope containing the module's global names.

  20. Python Scoping Rules

    An enclosing scope occurs when we have nested functions. When the variable is in the scope of the outside function, it means that the variable is in the enclosing scope of the function. Therefore, the variable is visible within the scope of the inner and outer functions. Enclosing Scope is often called non-local scope. def foo():

  21. Referenced before assignment Python

    It's hard to tell from what you've pasted, because you've clearly broken the indentation. But it looks like this code: print "Enter how many numbers you will enter." print "Maximum amount is 10: ". … is meant to be inside general, while this code: aon = raw_input() try: aon = int(aon) if aon >= 10: