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. 1 st condition is if the weight of the item is greater than 40 then the price will be Rs 100. 2 nd condition is if the weight of the item is greater th