Skip to main content

Section 2.16 Updating Variables: Compound Assignment

Updating variables is a very common operation in Python programs. Consider these updates:
x = 29
x = x + 1   # now 30
x = x - 5   # now 25
x = x * 3   # now 75
x = x / 4   # now 18.75
print(x)
When the variable on the left side of the assignment operator is the same as the variable on the right side, you can use a shortcut called compound assignment. Instead of saying x = x + 1, you can write x += 1. If you read x = x + 1 as “x becomes x + 1”, you can read x += 1 as “x plus-and-becomes 1.”
Table 2.16.1 gives a examples of the arithmetic operators and their compound assignment shortcuts.
Table 2.16.1. Compound Assignments
Assignment Compound Assignment
n = n + 3 n += 3
x = x - 4.2 x -= 4.2
y = y * 6 y *= 6
z = z / 5 z /= 5
x = x // 3 x //= 3
n = n % 7 n %= 7
We can, therefore, rewrite the example at the top of the page using compound assignment:
The update expression doesn’t have to be a simple variable: x = x + (y / z) can be shortened to x += (y / z). However, if the variable on the left-hand side is part of a parenthesized expression on the right, such as x = (x + 5) / 3, you cannot shorten it with compound assignment.

Checkpoint 2.16.2.

    What is printed when the following statements execute?
    n = 12
    n -= 3
    n *= 8
    n //= 2
    n %= 5
    
    print(n)
    
  • 12
  • The value of n changes in the second statement.
  • 2
  • Each statement changes the value of n, so 2 is not the final result.
  • 1
  • Yes, starting with 12, subtract 3, multiply by 8, integer divide by 2, and then take remainder after dividing by 5.
  • Nothing. An error occurs because n cannot be used that many times in compound assignment statements.
  • Remember that variables in Python are different from variables in math in that they (temporarily) hold values, but can be reassigned.