Practice With Arithmetic Operators

Practice these programming examples to internalize these concepts.

9. Assignment Operators

The most common assignment operator is one you have already used: the equals sign =. The = assignment operator assigns the value on the right to a variable on the left. For example, v = 23 assigns the value of the integer 23 to the variable v.

When programming, it is common to use compound assignment operators that perform an operation on a variable’s value and then assign the resulting new value to that variable. These compound operators combine an arithmetic operator with the = operator, so for addition we’ll combine + with = to get the compound operator +=. Let’s see what that looks like:

w = 5
w += 1



First, we set the variable w equal to the value of 5, then we used the += compound assignment operator to add the right number to the value of the left variable and then assign the result to w.


Compound assignment operators are used frequently in the case of for loops, which you’ll use when you want to repeat a process several times:

for x in range (0, 7):
    x *= 2



With the for loop, we were able to automate the process of the *= operator that multiplied the variable w by the number 2 and then assigned the result in the variable w for the next iteration of the for loop.

Python has a compound assignment operator for each of the arithmetic operators discussed in this tutorial:

y += 1 # add then assign value
y -= 1 # subtract then assign value
y *= 2 # multiply then assign value
y /= 3 # divide then assign value
y // = 5 # floor divide then assign value
y **= 2 # increase to the power of then assign value
y %= 3 # return remainder then assign value

Compound assignment operators can be useful when things need to be incrementally increased or decreased, or when you need to automate certain processes in your program.