As we have mentioned previously, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value).
The first time price is printed, its value is 11.95, and the second time, its value is 10.88. The assignment statement changes the value (the object) that price refers to.
Here is what reassignment looks like in a reference diagram:
In Python, an assignment statement can make two variables refer to the same object and therefore have the same value. They appear to be equal. However, because of the possibility of reassignment, they don’t have to stay that way:
Line 4 changes the value of a but does not change the value of b, so they are no longer equal. We will have much more to say about equality in a later chapter.
Subsection2.14.1Developing your Mental Model of How Python Evaluates
It’s important to start to develop a good mental model of the steps Python takes when evaluating an assignment statement. In an assignment statement, Python first evaluates the code on the right hand side of the assignment operator. It then gives a name to whatever that is. The (very short) visualization below shows what is happening.
Checkpoint2.14.1.
a = 5
b = a
In the first statement a = 5 the literal number 5 evaluates to 5, and is given the name a. In the second statement, the variable a evaluates to 5 and so 5 now ends up with a second name b.
Note2.14.2.
In some programming languages, a different symbol is used for assignment, such as <- or :=. The intent is that this will help to avoid confusion. Python chose to use the token = for assignment. This is a popular choice also found in languages like C, C++, Java, and C#.
Checkpoint2.14.3.
After the following statements, what are the values of x and y?
x = 15
y = x
x = 22
x is 15 and y is 15
Look at the last assignment statement, which gives x a different value.
x is 22 and y is 22
No, x and y are two separate variables. Just because x changes in the last assignment statement, it does not change the value that was copied into y in the second statement.
x is 15 and y is 22
Look at the last assignment statement, which reassigns x, and not y.