Python Compound Arithmetic Assignment Tutorial

Final Exam & Certification

Complete this tutorial and pass the 10-question final exam to earn a downloadable certificate of completion.

skip to exam

Python compound arithmetic assignment operators let you update a variable's value in a single, readable line. Instead of writing x = x + 5, you write x += 5. This tutorial covers all seven compound arithmetic assignment operators, how Python evaluates them, where they save you from common bugs, and how they behave with different data types.

What's in this Python Tutorial

Every time you increment a counter, accumulate a running total, or update a value inside a loop, you are performing an operation that compound assignment was built for. Knowing these operators will make your code shorter, easier to read, and less prone to the kind of typo that comes from repeating a variable name twice on the same line.

What Are Compound Assignment Operators?

A compound assignment operator — also called an augmented assignment operator — merges an arithmetic operation and an assignment into one expression. The general pattern is:

python
# Long form
x = x + value

# Compound form — identical result
x += value

Python evaluates the right-hand side first, applies the arithmetic operation to the current value of the variable on the left, and then assigns the result back to that variable. The variable must already exist before a compound assignment can be used — you cannot use += to initialize a variable that has never been assigned.

Note

Python does not have ++ or -- increment and decrement operators like C or Java do. The Python way to increment a variable is x += 1.

The Seven Operators at a Glance

Python provides seven compound assignment operators that correspond to the seven basic arithmetic operations.

Operator Name Equivalent To Example Result (x=10)
+=Add and assignx = x + nx += 313
-=Subtract and assignx = x - nx -= 37
*=Multiply and assignx = x * nx *= 330
/=Divide and assignx = x / nx /= 42.5
//=Floor divide and assignx = x // nx //= 33
%=Modulo and assignx = x % nx %= 31
**=Exponentiate and assignx = x ** nx **= 2100
code builder click a token to place it

Build a statement that multiplies score by 2 and assigns the result back to score:

your code will appear here...
2 score += *= score * 2
Correct answer: score *= 2. The *= operator multiplies score by 2 and assigns the result back to score in one step. Using += would add instead of multiply, and score * 2 is an expression, not a valid assignment target.

Each Operator in Detail

+= (Add and Assign)

The most commonly encountered compound operator. It adds the right-hand value to the variable and stores the result. It appears constantly in loop counters, running totals, and score accumulators.

python
total = 0
prices = [12.99, 4.50, 7.25, 19.00]

for price in prices:
    total += price

print(total)  # 43.74

-= (Subtract and Assign)

Subtracts the right-hand value from the variable. Common in countdown timers, inventory deductions, and remaining-balance calculations.

python
budget = 500.00
expenses = [45.00, 120.50, 30.00]

for expense in expenses:
    budget -= expense

print(f"Remaining budget: ${budget:.2f}")  # Remaining budget: $304.50

*= (Multiply and Assign)

Multiplies the variable by the right-hand value. Useful for applying percentage changes, scaling values, or building up exponential sequences manually.

python
# Apply 10% monthly growth for 3 months
value = 1000.00

for month in range(3):
    value *= 1.10

print(f"${value:.2f}")  # $1331.00

/= (Divide and Assign)

/= performs true division and always returns a float, even when both operands are integers. This is a significant difference from the //= operator and a frequent source of type surprises for beginners.

python
x = 10
x /= 4
print(x)        # 2.5
print(type(x))  # <class 'float'>

y = 8
y /= 2
print(y)        # 4.0  — still a float, even though it divides evenly
Watch Out

If your code expects an integer after a division, use //= instead of /=. Using /= on what you expect to remain an integer will silently convert it to a float, which may cause errors downstream when the value is passed to a function expecting an int.

//= (Floor Divide and Assign)

Divides the variable and rounds the result down to the nearest whole number. When both operands are integers, the result is an integer. When either operand is a float, the result is a float, but the value is still floored.

python
pages = 100
pages_per_chapter = 7

chapters_complete = pages
chapters_complete //= pages_per_chapter
print(chapters_complete)  # 14  (integer, not 14.28...)

# Floor division always rounds toward negative infinity
negative = -10
negative //= 3
print(negative)  # -4  (not -3)

%= (Modulo and Assign)

Assigns the remainder of dividing the variable by the right-hand value back to the variable. The modulo operator is widely used for cyclic indexing, determining even or odd values, and wrapping counters around a fixed range.

python
# Wrap a counter from 0 to 4 (five states)
counter = 0
for _ in range(12):
    print(counter, end=" ")
    counter += 1
    counter %= 5

# Output: 0 1 2 3 4 0 1 2 3 4 0 1
Pro Tip

You can combine += and %= into a single line using counter = (counter + 1) % 5 for clarity, but using them as separate compound assignments makes each step explicit and easier to debug.

**= (Exponentiate and Assign)

Raises the variable to the power of the right-hand value and assigns the result. Less common in everyday code than the others, but useful in mathematical and scientific computations involving powers, squares, or cubes.

python
base = 2
base **= 8
print(base)  # 256

# Works with floats too
radius = 5.0
radius **= 2
print(radius)  # 25.0
spot the bug click the line that contains the bug

The function below is supposed to halve a number using floor division, but it gives the wrong result. Click the line that contains the bug.

1 def halve(n):
2 """Return n halved, rounded down."""
3 result = n
4 result /= 2
5 return result
6 print(halve(9)) # Expected: 4, Got: 4.5
The fix: Change result /= 2 to result //= 2. The /= operator always performs true division and returns a float (4.5), but the function is documented to return the value rounded down. Floor division with //= returns the integer 4 as expected.

How to Use Compound Assignment Operators in Python

The process for applying compound assignment operators is straightforward. The key decisions are which operator to choose and confirming the type the result will produce.

  1. Choose the right operator for your arithmetic operation

    Identify whether you need addition (+=), subtraction (-=), multiplication (*=), true division (/=), floor division (//=), modulo (%=), or exponentiation (**=). The choice of /= versus //= is particularly important when you need an integer result.

  2. Replace the long-form assignment with the compound operator

    Write the variable name on the left, the compound operator in the middle, and the value or expression on the right. For example, replace score = score + 10 with score += 10. The variable on the left must already be defined before this line runs.

  3. Verify the result is what you expect

    Print the variable after the operation, or step through the code in a debugger. Pay special attention to the type of the result — /= will always produce a float — and to behavior with negative numbers when using //=, since floor division rounds toward negative infinity, not toward zero.

Behavior with Different Data Types

Compound assignment operators are not limited to numbers. Python's data model allows objects to define how augmented assignment works through dunder methods, which means += and *= have meaningful behavior on strings and lists as well.

python
# Strings — += concatenates
greeting = "Hello"
greeting += ", world!"
print(greeting)  # Hello, world!

# Strings — *= repeats
separator = "-"
separator *= 20
print(separator)  # --------------------

# Lists — += extends in place (calls __iadd__, modifies the original list)
items = [1, 2, 3]
items += [4, 5]
print(items)  # [1, 2, 3, 4, 5]

# Lists — *= repeats the list in place
flags = [False]
flags *= 4
print(flags)  # [False, False, False, False]

The distinction between immutable and mutable types is important here. For integers and strings (immutable), Python creates a new object and rebinds the variable name to it. For lists (mutable), += calls the list's __iadd__ method, which modifies the object in place. This matters when multiple variables point to the same list.

python
# Integers: rebinds variable — original object unchanged
a = 10
b = a
a += 5
print(a)  # 15
print(b)  # 10 — b still points to the original object

# Lists: modifies in place — both variables see the change
x = [1, 2, 3]
y = x
x += [4]
print(x)  # [1, 2, 3, 4]
print(y)  # [1, 2, 3, 4] — y sees the change because x and y share the same object
"Augmented assignments can be used to redefine the augmented assignment." — Python Language Reference

Python Learning Summary Points

  1. Compound arithmetic assignment operators combine an arithmetic operation and an assignment in a single expression. The variable on the left must already exist before the operator is used.
  2. /= always produces a float. When you need an integer result from division, use //= instead. This is the most common source of type-related bugs with these operators.
  3. Compound assignment behavior depends on the data type. For mutable types such as lists, += modifies the object in place rather than creating a new one, which affects all variables that reference the same object.

Compound arithmetic assignment operators are a small feature with a large impact on code quality. Once they become habit, you will find that your loops, accumulators, and update expressions become noticeably cleaner and less error-prone. The next step is to explore Python's bitwise compound assignment operators — &=, |=, ^=, >>=, and <<= — which follow exactly the same pattern applied to bit-level operations.

check your understanding question 1 of 5

Frequently Asked Questions

A compound arithmetic assignment operator combines an arithmetic operation with an assignment in a single step. For example, x += 5 adds 5 to x and assigns the result back to x, which is equivalent to writing x = x + 5. This makes code shorter and reduces the risk of typos from repeating the variable name.

Python provides seven compound arithmetic assignment operators: += (add and assign), -= (subtract and assign), *= (multiply and assign), /= (divide and assign, always returns a float), //= (floor divide and assign), %= (modulo and assign), and **= (exponentiate and assign).

/= performs true division and always returns a float, even when dividing two integers. For example, x = 8; x /= 2 gives 4.0, not 4. //= performs floor division, rounding down to the nearest whole number and preserving the integer type when both operands are integers. For example, x = 8; x //= 2 gives 4.

Yes. The += operator works with strings to concatenate them and with lists to extend them in place. The *= operator repeats a string or list. For lists, += is equivalent to calling the .extend() method, which modifies the list in place and is more efficient than using + to create a new list.

It depends on the type. For immutable types such as integers and strings, Python creates a new object and rebinds the variable to it. For mutable types such as lists, the __iadd__ dunder method is called, which modifies the object in place without creating a new one. This means that if two variables reference the same list, both will see the change after +=.

The %= operator assigns the remainder of dividing the variable by a value back to the variable. For example, x %= 3 is equivalent to x = x % 3. It is commonly used in loops to cycle through a fixed range of values or to determine whether a number is even or odd.

Python does not have a ++ increment operator. The correct way to increment a variable by one in Python is x += 1, which is equivalent to x = x + 1. Writing x++ in Python raises a SyntaxError.

The **= operator raises the variable to the power of the right-hand operand and assigns the result back to the variable. For example, x **= 3 is equivalent to x = x ** 3. If x is 2, the result is 8.

Certificate of Completion
Final Exam
Pass mark: 80% · Score 80% or higher to receive your certificate

Enter your name as you want it to appear on your certificate, then start the exam. Your name is used only to generate your certificate and is never transmitted or stored anywhere.

Question 1 of 10