Augmented Assignment Operators
In the pevious lesson, we discussed the Arithmetic Operators. These are operator that we are used to even right from school. In this lesson we will discuss different types of operator that are a bit peculiar: Augmented assignment operators.
Augmented assignment operators allow you to perform an operation and assign the result to a variable in a compact way.
What Are Augmented Assignment Operators?
They are shortcuts to perform some repetitive operations. For example, instead of writing:
x = x + 5
You can use an augmented assignment operator:
x += 5
Python provides several augmented assignment operators:
Operator | Example | Equivalent To | Description |
---|---|---|---|
+= |
x += 5 |
x = x + 5 |
Adds and assigns the result |
-= |
x -= 3 |
x = x - 3 |
Subtracts and assigns the result |
*= |
x *= 2 |
x = x * 2 |
Multiplies and assigns the result |
/= |
x /= 4 |
x = x / 4 |
Divides and assigns the result (float result) |
//= |
x //= 2 |
x = x // 2 |
Floor divides and assigns the result |
%= |
x %= 3 |
x = x % 3 |
Modulus and assigns the result |
**= |
x **= 2 |
x = x ** 2 |
Raises to power and assigns the result |
Examples of Augmented Assignment Operators
x = 10
x += 5 # Equivalent to x = x + 5
print(x) # Output: 15
y = 20
y -= 3 # Equivalent to y = y - 3
print(y) # Output: 17
z = 2
z **= 3 # Equivalent to z = z ** 3
print(z) # Output: 8
Why Use Augmented Assignment Operators?
- They make code shorter and more readable.
- They improve performance slightly by modifying variables in place.
Exercise: Try It Yourself!
- Initialize
a = 12
and use+=
to add8
to it. - Initialize
b = 25
and use-=
to subtract10
from it. - Initialize
c = 4
and use**=
to raise it to the power of3
. - Predict and print the result of
x = 20; x //= 6
.