How Compound Operators Work in Python: Examples Explained

Before entering into how Compound Operators work in python, Let’s understand it first.

What Are Compound Operators?

Basically, Compound operators, often called shorthand operators, combine arithmetic, bitwise, or logical operations with assignment. They make the code cleaner and reduce redundancy. It also shorten the length of program. For instance, instead of saying, “Add b to a and then store it back in a,” you can just write a += b.

In Python, compound operators provide a concise way to perform operations and assign the result back to the variable. Instead of writing long expressions like a = a + b, you can use a += b. It’s simple, effective, and enhances code readability. Let’s explore how compound operators work using two variables: a = 5 and b = 6.

Examples of Compound Operators in Python

To understand their functionality, we have taken example of two variables for some common compound operators with a = 5 and b = 6.

Syntax to compound operators:

result_v operator = operand_v

Example: balance = balance + deposit is same as balance += deposit

Compound Operators

a+=b #Addition Assignment
a-=b #Subtraction Assignment
a*=b #Multiplication Assignment
a//=b #Quotient Assignment
a%=b #Remainder Assignment
a**=b #Square Assignment

Addition Assignment (+=)

This operator adds the value of b to a.
a += b  # Equivalent to a = a + b  
print(a)  # Output: 11  

Subtraction Assignment (-=)

-= subtracts b from a
a -= b  # Equivalent to a = a - b  
print(a)  # Output: -1 

Multiplication Assignment (*=)

Want to multiply and update? Use *=.
a *= b  # Equivalent to a = a * b  
print(a)  # Output: 30  

Division Assignment (/=)

When dividing, Python ensures the result is a float.
a /= b  # Equivalent to a = a / b  
print(a)  # Output: 0.8333...

Floor Division Assignment (//=)

a //= b  # Equivalent to a = a // b
Before: a = 5
Operation: a = 5 // 6
After: a = 0 (integer division)

Modulus Assignment (%=)

a %= b  # Equivalent to a = a % b
Before: a = 5
Operation: a = 5 % 6
After: a = 5 (remainder of division)

Exponentiation Assignment (**=)

a **= b  # Equivalent to a = a ** b
Before: a = 5
Operation: a = 5 ** 6
After: a = 15625

Bitwise Operators

Bitwise AND (&=): a &= b
Bitwise OR (|=): a |= b
Bitwise XOR (^=): a ^= b
Left Shift (<<=): a <<= b
Right Shift (>>=): a >>= b

Leave a Reply

Your email address will not be published. Required fields are marked *