As you may have discovered, 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 we display x, its value is 5; the second time, its value is 7.
Figure 11.1 shows what reassignment looks like in a state diagram.
At this point I want to address a common source of confusion. Because Python uses the equal sign (=) for assignment, it is tempting to interpret a statement like a = b as a mathematical proposition of equality; that is, the claim that a and b are equal. But this interpretation is wrong.
First, equality is a symmetric relationship and assignment is not. For example, in mathematics, if then . But in Python, the statement a = 7 is legal and 7 = a is not.
Also, in mathematics, a proposition of equality is either true or false for all time. If now, then will always equal . In Python, an assignment statement can make two variables equal, but they don’t have to stay that way:
The third line changes the value of a but does not change the value of b, so they are no longer equal.
Reassigning variables is often useful, but you should use it with caution. If the values of variables change frequently, it can make the code difficult to read and debug.
A common kind of reassignment is an update, where the new value of the variable depends on the old.
This means “get the current value of x, add one, and then update x with the new value.”
If you try to update a variable that doesn’t exist, you get an error, because Python evaluates the right side before it assigns a value to x:
Before you can update a variable, you have to initialize it, usually with a simple assignment:
Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.
Updating variables using an operator is so common that Python has a shorter way to write it:
These are called in-place operators.