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?