Python Arithmetic Assignment Operators

This article is a complementary resource to the Learn Python Basics course.

Python Arithmetic Assignment Operators

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.


List of Arithmetic Assignment Operators

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.

Example: Subtraction with -= Operator

total = 100
discount = 20

total -= discount

print(total)    # Output: 80

Example: Division with /= Operator

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!