Arithmetic Assignment Operators #
You may have noticed that sometimes you need to write an assignment statement that uses the current value of the variable being assigned to. For example:
x = x + 1
You can write this a bit more concisely, as x += 1
. You can actually do this
with any arithmetic operator on a numeric variable:
x = 10
x += 5 # x is 15
x //= 3 # x is 5
x **= 2 # x is 25
The +=
operator also work with strings:
s = "sp"
s += "am" # s is "spam"