Skip to main content

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

Popular posts from this blog

Difference between Web Designer and Web Developer Neeraj Mishra The Crazy Programmer

Have you ever wondered about the distinctions between web developers’ and web designers’ duties and obligations? You’re not alone! Many people have trouble distinguishing between these two. Although they collaborate to publish new websites on the internet, web developers and web designers play very different roles. To put these job possibilities into perspective, consider the construction of a house. To create a vision for the house, including the visual components, the space planning and layout, the materials, and the overall appearance and sense of the space, you need an architect. That said, to translate an idea into a building, you need construction professionals to take those architectural drawings and put them into practice. Image Source In a similar vein, web development and design work together to create websites. Let’s examine the major responsibilities and distinctions between web developers and web designers. Let’s get going, shall we? What Does a Web Designer Do?

A guide to data integration tools

CData Software is a leader in data access and connectivity solutions. It specializes in the development of data drivers and data access technologies for real-time access to online or on-premise applications, databases and web APIs. The company is focused on bringing data connectivity capabilities natively into tools organizations already use. It also features ETL/ELT solutions, enterprise connectors, and data visualization. Matillion ’s data transformation software empowers customers to extract data from a wide number of sources, load it into their chosen cloud data warehouse (CDW) and transform that data from its siloed source state, into analytics-ready insights – prepared for advanced analytics, machine learning, and artificial intelligence use cases. Only Matillion is purpose-built for Snowflake, Amazon Redshift, Google BigQuery, and Microsoft Azure, enabling businesses to achieve new levels of simplicity, speed, scale, and savings. Trusted by companies of all sizes to meet

2022: The year of hybrid work

Remote work was once considered a luxury to many, but in 2020, it became a necessity for a large portion of the workforce, as the scary and unknown COVID-19 virus sickened and even took the lives of so many people around the world.  Some workers were able to thrive in a remote setting, while others felt isolated and struggled to keep up a balance between their work and home lives. Last year saw the availability of life-saving vaccines, so companies were able to start having the conversation about what to do next. Should they keep everyone remote? Should they go back to working in the office full time? Or should they do something in between? Enter hybrid work, which offers a mix of the two. A Fall 2021 study conducted by Google revealed that over 75% of survey respondents expect hybrid work to become a standard practice within their organization within the next three years.  Thus, two years after the world abruptly shifted to widespread adoption of remote work, we are declaring 20