Augmented assignments (+=, -=, etc.) in Python (8/100 Days of Python)
In Python, you can use shorthands to perform arithmetic operations and assign the result to a variable at the same time. This can be a convenient way to write code and can save you some typing:
x = 10
y = 5
# Shorthand for x = x + y
x += y # x is now 15
# Shorthand for x = x - y
x -= y # x is now 10
# Shorthand for x = x * y
x *= y # x is now 50
# Shorthand for x = x / y
x /= y # x is now 10.0
# Shorthand for x = x % y
x %= y # x is now 0
These shorthands can be used with any arithmetic operator (+
, -
, *
, /
, %
, etc.). They can also be used with multiple variables.
It’s important to note that these shorthands only work with variables. You cannot use them to perform arithmetic operations on literal values. For example, the following code would produce an error:
x = 10
y = 5
z = 2
# Shorthand for x = x + y + z
x += y + z # x is now 17
# This would produce an error
10 += 5
In literature, these types of operations are often referred to as “augmented assignments” or “compound assignments”. They are called “augmented” because they augment the value of a variable by performing an operation on it, and “compound” because they combine an operation with an assignment.
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course — Arithmetic operations
- Full series: 100 Days of Python
- Previous topic: Floating point numbers
- Next topic: Strings