Читать книгу Learn Python quick - Jens Braun - Страница 13
More Assignment Operators
ОглавлениеBesides the = sign, there are a few more assignment operators in Python (and most programming languages). These include operators like +=, -= and *=.
Suppose we have the variable x, with an initial value of 10. If we want to increment x by 2, we can write
x = x + 2
The program will first evaluate the expression on the right (x + 2) and assign the answer to the left. So eventually the statement above becomes x <- 12.
Instead of writing x = x + 2, we can also write x += 2 to express the same meaning. The += sign is actually a shorthand that combines the assignment sign with the addition operator. Hence, x += 2 simply means x = x + 2.
Similarly, if we want to do a subtraction, we can write x = x - 2 or x -= 2. The same works for all the 7 operators mentioned in the section above.