Local variable referenced before assignment: The UnboundLocalError in Python

When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. Because you try to use a local variable referenced before assignment. So, in this guide, we talk about what this error means and why it is raised. We walk through an example in action to help you understand how you can solve it.

Source: careerkarma

Local variable referenced before assignment

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:

1 UnboundLocalError: local variable referenced before assignment

Python has a simple rule to determine the scope of a variable. To clarify, a variable is assigned in a function, that variable is local. 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. Whereas, local variables are only accessible within the function in which they are originally defined.

An example of Local variable referenced before assignment

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

Firstly, we start by declaring two variables:

1 numerical = 36
2 letter = "F"

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

1 def calculate_grade(grade):
2    if grade > 80:
3        letter = "A"
4    elif grade > 70:
5       letter = "B"
6    elif grade > 60:
7       letter = "C"
8    elif grade > 50:
9        letter = "D"
10    return letter

Finally, we call our function:

1 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 of Local variable referenced before assignment and see what happens:

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

Here is an error!

The Solution of Local variable referenced before assignment

The code returns an error: Unboundlocalerror local variable referenced before assignment 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.

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

Therefore, this problem of variable referenced before assignment could be solved in two ways. Firstly, we can add an else statement to our code. This ensures we declare “letter” before we try to return it:

1 …
2 elif grade > 50:
3    letter = "D"
4 else:
5    letter = "F"
6 return letter

Let’s try to run our code again:

1 F

Our code successfully prints out the student’s grade. This approach is good because it lets us keep “letter” in the local context. To clarify, we could even remove the “letter = “F”” statement from the top of our code because we do not use it in the global context.

Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our calculate_grade() function:

1 def calculate_grade(grade):
2    global letter
3    if grade > 80:
4       letter = "A"
5    elif grade > 70:
6        letter = "B"
7    elif grade > 60:
8       letter = "C"
9    elif grade > 50:
10        letter = "D"
11    return letter

We use the “global” keyword at the start of our function.

This keyword changes the scope of our variable to a global variable. This means the “return” statement will no longer treat “letter” like a local variable. Let’s run our code. Our code returns: F.

The code works successfully! Let’s try it using a different grade number by setting the value of “numerical” to a new number:

1 numerical = 73

Our code returns: B.

Finally, we have fixed the local variable referenced before assignment error in the code.

Conclusion

To sum up, as you can see, 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. Then, you can solve this error by ensuring that a local variable is declared before you assign it a value. Moreover, if a variable is declared globally that you want to access in a function, you can use the “global” keyword to change its value. In case you have any inquiry, let’s CONTACT US. With a lot of experience in Mobile app development services, we will surely solve it for you instantly.

Tags

Share