AlgoCademy
Lesson
Code

Mathematical Assignment Operators in {lang}


In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:

myVar = myVar + 5

to add 5 to myVar. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.

One such operator is the += operator:

myVar = 10
myVar += 5
print(myVar)

15 would be logged to the console.


There is one such operator for every other arithmetic operator we've learned:

For subtraction: -=

myVar = 10
myVar -= 5 # short for myVar = myVar - 5
print(myVar) # Prints 5

For multiplication: *=

myVar = 3
myVar *= 5 # short for myVar = myVar * 5
print(myVar) # Prints 15

For division: /=

myVar = 20
myVar /= 4 # short for myVar = myVar / 4
print(myVar) # Prints 5

For remainder: %=

myVar = 11
myVar %= 3 # short for myVar = myVar % 3
print(myVar) # Prints 2

For exponentiation: **=

myVar = 3
myVar **= 3 # short for myVar = myVar ** 3
print(myVar) # Prints 27

For floor division: //=

myVar = 20
myVar //= 3 # short for myVar = myVar // 3
print(myVar) # Prints 6


Assignment
Follow the Coding Tutorial and let's do some mathematical assignments.


Hint
Look at the ourName example above if you get stuck.