Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
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
printed, its value is 5, and the second time, its value is 7. The assignment statement changes
the value (the object) that
bruce refers to.
Here is what reassignment looks like in a reference diagram:
It is important to note that in mathematics, a statement of equality is always true. If
a is equal to b
a will always equal to b. 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.
2.12.1. Developing your mental model of How Python Evaluates¶
Its important to start to develop a good mental model of the steps the Python interpreter takes when evaluating an assignment statement. In an assignment statement, the interpreter 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.
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
You can step through the code and see how the variable assignments change below.
In some programming languages, a different
symbol is used for assignment, such as
:=. The intent is
that this will help to avoid confusion. Python
chose to use the tokens
= for assignment, and
== for equality. This is a popular
choice also found in languages like C, C++, Java, and C#.
Check your understanding