Referenced before assignment error

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

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

Why Does This Error Occur?

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

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

Local Variable Declarations vs. Global Variable Declarations

Local Variables Global Variables
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.
Local Variables can only be accessed within their own function. All functions of the program can access global variables.
Local variables are immune to changes in the global scope. Thereby being more secure. Global Variables are less safer from manipulation as they are accessible in the global scope.

“Other Commands Don’t Work After on_message” in Discord Bots

Local Variable Referenced Before Assignment Error with Explanation

Try these examples yourself using our Online Compiler.

Let’s look at the following function:

# Variable decleration outside function (global scope)
myVar = 10


def myFunction():
      if myVar == 5:
            print("5")
      elif myVar == 10:
            print("10")
      elif myVar >= 15:
            print("greater than 15 ")
     # reassigning myVar in the function
      myVar = 0

myFunction()

Output

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.

Solutions

Using Global Variables

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

myVar = 10
def myFunction():
     # Telling the function to consider myVar as global
      global myVar
      if myVar == 5:
            print("5")
      elif myVar == 10:
            print("10")
      elif myVar >= 15:
            print("greater than 15 ")
      myVar = 0

myFunction()

Output

10

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.

# Passing myVar as a parameter in the function
def myFunction(myVar):
      if myVar == 5:
            print("5")
      elif myVar == 10:
            print("10")
      elif myVar >= 15:
            print("greater than 15 ")
      myVar = 0

myFunction(10)

Output

10

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.

$ anaconda-navigator          
Traceback (most recent call last):
  File "/home/user/anaconda3/lib/python3.7/site-packages/anaconda_navigator/widgets/main_window.py", line 541, in setup
    self.post_setup(conda_data=conda_data)
...
...
UnboundLocalError: local variable 'DISTRO_NAME' referenced before assignment

Solution 1

Try and update your Anaconda Navigator with the following command.

conda update anaconda-navigator

Solution 2

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

.../anaconda3//lib/python3.7/site-packages/anaconda_navigator/api/external_apps/vscode.py

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.

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

from django import forms


# Creating a Class for django forms
class MyForm(forms.Form):
    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    msg = forms.CharField(
        required=True,
        widget=forms.Textarea
    )


...
# Create a function to retrieve info from the form
def GetContact(request):
    form_class = ContactForm
    if request.method == 'POST':
        form = form_class(request.POST)

        # Upon verifying validity, get following info and email with said info
        if form.is_valid():
            name = request.POST.get('name')
            email = request.POST.get('email')
            msg = request.POST.get('msg')

            send_mail('Subject here', msg, email, ['[email protected]'], fail_silently=False)
            return HttpResponseRedirect('blog/inicio')
            return render(request, 'blog/inicio.html', {'form': form})
...

Upon running you get the following error:

local variable 'form' referenced before assignment

Explanation

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

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

Why does the error occur?

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

FAQs on Local Variable Referenced Before Assignment

How would you avoid using a global variable in multi-threads?

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.

Conclusion

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

  • “Other Commands Don’t Work After on_message” in Discord Bots

    “Other Commands Don’t Work After on_message” in Discord Bots

    February 5, 2023

  • Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    by Rahul Kumar YadavFebruary 5, 2023

  • [Resolved] NameError: Name _mysql is Not Defined

    [Resolved] NameError: Name _mysql is Not Defined

    by Rahul Kumar YadavFebruary 5, 2023

  • Best Ways to Implement Regex New Line in Python

    Best Ways to Implement Regex New Line in Python

    by Rahul Kumar YadavFebruary 5, 2023

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:

test_var = 0

def test_func(test_var):
    test_var += 1
    return test_var

test_func(test_var)

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

test_var = 0

def test_func():
    global test_var
    test_var += 1
    return test_var

test_func()

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

What is Scope in Python?

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

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: local variable referenced before assignment

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:

var = 10

def test_func():
    print(var)

test_func()
10

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

var = 10

def test_func():
    var += 1
    print(var)
test_func()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Input In [17], in <cell line: 6>()
      4     var += 1
      5     print(var)
----> 6 test_func()

Input In [17], in test_func()
      3 def test_func():
----> 4     var += 1
      5     print(var)

UnboundLocalError: local variable 'var' referenced before assignment

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.

number = 10

def increment_func():
    number += 1
    return number

print(increment_func())

Let’s run the code to see what happens:

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Input In [19], in <cell line: 7>()
      4     number += 1
      5     return number
----> 7 print(increment_func())

Input In [19], in increment_func()
      3 def increment_func():
----> 4     number += 1
      5     return number

UnboundLocalError: local variable 'number' referenced before assignment

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

Solution #1: Passing Parameters to the Function

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:

number = 10

def increment_func(number):

    number += 1

    return number

print(increment_func(number))

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:

11

We successfully printed the value to the console.

Solution #2: Use Global Keyword

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:

number = 10

def increment_func():

    global number

    number += 1

    return number

print(increment_func())

Let’s run the code to see the result:

11

We successfully printed the value to the console.

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.

score = int(input("Enter your score between 0 and 100: "))

def calculate_level(score):

    if score > 90:

        level = 'expert'

    elif score > 70:

        level = 'advanced'

    elif score > 55:

        level = 'intermediate'

    return 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:

print(f'Your level is: {calculate_level(score)}')
Enter your score between 0 and 100: 40

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Input In [12], in <cell line: 1>()
----> 1 print(f'Your level is: {calculate_level(score)}')

Input In [11], in calculate_level(score)
      7 elif score > 55:
      8     level = 'intermediate'
----> 9 return level

UnboundLocalError: local variable 'level' referenced before assignment

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.

Solution #1: Include else statement

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:

score = int(input("Enter your score between 0 and 100: "))

def calculate_level(score):

    if score > 90:

        level = 'expert'

    elif score > 70:

        level = 'advanced'

    elif score > 55:

        level = 'intermediate'

    else:

        level = 'beginner'

    return level

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

print(f'Your level is: {calculate_level(score)}')
Enter your score between 0 and 100: 40

Your level is: beginner

Solution #2: Use global keyword

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.

score = int(input("Enter your score between 0 and 100: "))

level = 'beginner'

def calculate_level(score):

    global level

    if score > 90:

        level = 'expert'

    elif score > 70:

        level = 'advanced'

    elif score > 55:

        level = 'intermediate'

    return level

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:

print(f'Your level is: {calculate_level(score)}')
40 

Your level is: beginner

Summary

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!

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.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

What is UnboundLocalError: local variable referenced before assignment?

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

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

numerical = 36
letter = "F"

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:

def calculate_grade(grade):
	if grade > 80:
		letter = "A"
	elif grade > 70:
		letter = "B"
	elif grade > 60:
		letter = "C"
	elif grade > 50:
		letter = "D"
	return letter

Finally, we call our function:

print(calculate_grade(numerical))

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:

Traceback (most recent call last):
  File "main.py", line 15, in <module>
	print(calculate_grade(numerical))
  File "main.py", line 13, in calculate_grade
	return letter
UnboundLocalError: local variable 'letter' referenced before assignment

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:

def calculate_grade(grade):
	if grade > 80:
		letter = "A"
	elif grade > 70:
		letter = "B"
	elif grade > 60:
		letter = "C"
    elif grade > 50:
        letter = "D"
    else:
        letter = "F"
    return letter

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.

Conclusion

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!

While we are learning about functions, or using functions to write a program, we often encounter an error called: UnboundLocalError: local variable referenced before assignment.

In this article, we will see what causes this error and how can we eliminate this type of error in our programs.

Reasons for Error

Case 1:

Suppose we write a function to calculate a price for the given weight.

For example:

def get_price(weight):

    if (weight > 40):

        price = 100

    elif (weight > 20):

        price = 50

    return price

print(f«Price is : {get_price(weight=25)}»)

print(f«Price is : {get_price(weight=15)}»)

In the above example, we have written a function named get_price(). Which will return’s a price tag for the given input of weight. Here we have introduced 2 conditions to consider the price.

1st condition is if the weight of the item is greater than 40 then the price will be Rs 100.

2nd condition is if the weight of the item is greater than 20, then the price will be Rs 50.

When we call the function first time and pass weight as 25, then the function will work well and return 50.

Output:

Price is : 50

This function will work well when we pass the weight of the item greater than 20. But wait, what if we pass the weight less than 20 ?.

As in 2nd time when we are calling the function and pass value of weight as 15 then,

It will throw an error called:

Traceback (most recent call last):

  File “c:UsersASUSDesktopprogramsmain.py”, line 13, in <module>

    print(get_price(weight=15))

  File “c:UsersASUSDesktopprogramsmain.py”, line 10, in get_price

    return price

UnboundLocalError: local variable ‘price’ referenced before assignment

This error occurs because as we can see in the function that we have defined only 2 conditions but the weight we are passing to the function does not come under any condition so that the execution of the program will not go in any of the if block.

It directly comes to the line where the function is going to return something. Since we can see that we have written to return price, we have not defined what price to be returned because the function is not able to recognize it. Therefore, it shows this error.

Case 2:

We can encounter this error we are directly trying to access a global variable in our function.

For example:

num = 15

def add_number_by_1():

    num = num + 1

    return num

print(add_number_by_1())

In the above example, we are trying to add 1 to a num variable that is not defined in the function, when we execute the program then it will throw the same error.

Traceback (most recent call last):

  File “c:UsersASUSDesktopprogramsmain.py”, line 21, in <module>           print(add_number_by_1())

  File “c:UsersASUSDesktopprogramsmain.py”, line 16, in add_number_by_1

    num = num + 1

UnboundLocalError: local variable ‘num’ referenced before assignment

It is showing the error because the number in which we are trying to add 1 is not in the scope of the function itself. Therefore, the function is not able to recognize the value of the num variable.

Ways to Solve Error

Case 1:

So here comes the solution part, we have to keep some points in our minds whenever we are writing functions, As we know if we return something from a function, the variable which we are trying to return should be defined in the function itself. Because the scope of that variable will be limited to that function only. If it is defined in the function then the function will easily return the value. It will not throw any error in this case.

As we encountered an error in the previous example, we are going to see how can we eliminate this error.

Code:

def get_price(weight):

    if (weight > 40):

        price = 100

    elif (weight > 20):

        price = 50

    else:

        price = 25

    return price

print(f«Price is : {get_price(weight=25)}»)

print(f«Price is : {get_price(weight=15)}»)

Output:

Price is : 50

Price is : 25

As shown in the above example, we have added an else block in the function, so that if any of the condition does not come true then we will have else block to execute it and we will get the price value in this case which helps us to return that value from the function.

In this case, it will not show any error because the value we are trying to return is already defined in either of the conditions above.

The value can be from if block or elif block or else block. It depends of the conditions we have written in the function and the value of the weight we have passed to the function as input.

After the addition of the else block, the function get_price() will be executed in all conditions. Whatever will be the value of weight we pass to the function, we will get the respective output as price from the function.

Case 2:

As we have seen in case 2, we can solve this error by using a keyword called global. It helps to inform our function that the value of num which we are trying to access exists in the global scope and after this, our function will be able to recognize the value of num and we will be able to perform the respective operation on that variable.

Code:

num = 15

def add_number_by_1():

    global num

    num = num + 1

    return num

print(f«After adding 1 to {num}, it becomes {add_number_by_1()}»)

Output:

After adding 1 to 15, it becomes 16

Conclusion

Whenever we try to access a variable that is not defined earlier then we encounter this type of error. In this article, we have seen how UnboundLocalError: local variable referenced before assignment error occurs and we have seen the cases in which this error can occur. We also have seen the respective solutions of those cases.

Понравилась статья? Поделить с друзьями:
  • Reed solomon error correction
  • Reduce initial server response time как исправить
  • Removable disk как исправить
  • Remotr a network error has occurred check your internet connection and try again
  • Remote streamer a network error has occurred check your internet connection and try again