How does Python reassign a variable's value?


#1

Question

If a variable already has a value, how do we change that value later by reassigning a new value?

Answer

We can think of variables as being little boxes that are able to store values. In this exercise, we’ve labeled our box annual_rainfall and put the value of january_to_june_rainfall in it at first. When we assign a new value in that same variable, the number in our box is replaced by the values for the months from September through December.

In-depth Look at the Exercise

We start with the code below:

january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50
annual_rainfall = january_to_june_rainfall

july_rainfall = 1.05
annual_rainfall += july_rainfall

august_rainfall = 4.91
annual_rainfall += august_rainfall

september_rainfall = 5.16
october_rainfall = 7.20
november_rainfall = 5.06
december_rainfall = 4.06

The very first line of code, january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50, assigns the result of that addition to the variable named january_to_june_rainfall.
After that, three examples of using the += operator are given to give you an idea of how to update an existing variable’s value, annual_rainfall.
September through December, then, are the months we haven’t added to the existing variable’s value, which is the goal of the exercise.


FAQ: Learn Python - Python Syntax - Updating Variables
#2

5 posts were split to a new topic: Why January to June rainfall not January to August?


#3

A post was split to a new topic: Reassigning variable in python


#4

2 posts were split to a new topic: Can’t we just Add the Last Four Months All Together?


#5

2 posts were split to a new topic: How do I Change the july_rainfall Variable to 1.10?


#7

Hi, I am currently stuck on this exercise. I have the following code

september_to_december_rainfall = 5.16 + 7.20 + 5.06 + 4.06
annual_rainfall = september_to_december_rainfall

july_rainfall = 1.05
annual_rainfall += july_rainfall

august_rainfall = 4.91
annual_rainfall += august_rainfall

september_rainfall = 5.16
annual_rainfall += september_rainfall

october_rainfall = 7.20
annual_rainfall += october_rainfall

november_rainfall = 5.06
annual_rainfall += november_rainfall

december_rainfall = 4.06
annual_rainfall += december_rainfall

september_rainfall = 5.16
october_rainfall = 7.20
november_rainfall = 5.06
december_rainfall = 4.06

I am getting the response

Did you add all of the remaining months to the variable annual_rainfall?

I’m completely lost as I thought I added the remaining months (sept-dec) as I followed suit from July and Aug…


#8

If I am not wrong an answer to this exercise has been posted in detail.
This thread to delves into the concept.
Why January to June rainfall not January to August?.

Hope this helps.


#9

Yes, I found this.

I forgot to delete this post.

Thanks


#10

2 posts were split to a new topic: What’s Wrong with this Code?