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