Solve “local variable referenced before assignment” Error in Python Neeraj Mishra The Crazy Programmer
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:\Users\ASUS\Desktop\programs\main.py”, line 13, in <module>
print(get_price(weight=15))
File “c:\Users\ASUS\Desktop\programs\main.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:\Users\ASUS\Desktop\programs\main.py”, line 21, in <module> print(add_number_by_1())
File “c:\Users\ASUS\Desktop\programs\main.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.
The post Solve “local variable referenced before assignment” Error in Python appeared first on The Crazy Programmer.
from The Crazy Programmer https://ift.tt/3H5S7Cz
Comments
Post a Comment