Python Arithmetic Assignment Operators
This article is a complementary resource to the Learn Python Basics course.
This article is a complementary resource to the Learn Python Basics course.
Arithmetic assignment operators are shorthand operators in Python that combine arithmetic operations and assignments in a single step.
Suppose you want to increase the value of a variable by 1:
i = 10
i = i + 1
print(i) # Output: 11
This code adds 1 to the value of i and assigns the updated value back to the i variable.
In such cases, you can use arithmetic assignment operators to make the operation clearer and more concise:
i = 10
# Equivalent to: i = i + 1
i += 1
print(i) # Output: 11
Here, the += operator adds 1 to the variable i and updates its value.
Python supports arithmetic assignment operators for all standard arithmetic operators. Here's the summary:
| Operator | Example | Equivalent To |
|---|---|---|
+= |
x += 5 |
x = x + 5 |
-= |
x -= 5 |
x = x - 5 |
*= |
x *= 5 |
x = x * 5 |
//= |
x //= 5 |
x = x // 5 |
/= |
x /= 5 |
x = x / 5 |
%= |
x %= 5 |
x = x % 5 |
**= |
x **= 5 |
x = x ** 5 |
Let's see some of these operators in practice.
total = 100
discount = 20
total -= discount
print(total) # Output: 80
number = 1000.0
divisor = 5
number /= divisor
number /= divisor
print(number) # Output: 40.0
Now, try using arithmetic assignment operators in your code to make your operations more concise and readable!