2. Assignment Operators
Assignment operators are used to assign values to variables. These operators can also perform operations like addition, subtraction, etc., along with assignment, using a shorter syntax.
List of Assignment Operators
| Operator | Description | Example |
|---|---|---|
| = | Assigns value | x = 10 |
| += | Add and assign | x += 3 → x = x + 3 |
| -= | Subtract and assign | x -= 2 → x = x - 2 |
| *= | Multiply and assign | x *= 5 → x = x * 5 |
| /= | Divide and assign | x /= 4 → x = x / 4 |
| %= | Modulus and assign | x %= 2 → x = x % 2 |
| **= | Power and assign | x **= 3 → x = x ** 3 |
| //= | Floor divide and assign | x //= 2 → x = x // 2 |
Example:
x = 10
x += 5
print("After += :", x)
x *= 2
print("After *= :", x)
x //= 4
print("After //= :", x)
x **= 2
print("After **= :", x)
Output:
After += : 15
After *= : 30
After //= : 7
After **= : 49
Explanation:
x = 10→ Initial value of x is 10.x += 5→ Adds 5 to current value → 10 + 5 = 15.x *= 2→ Multiplies current value by 2 → 15 × 2 = 30.x //= 4→ Performs floor division by 4 → 30 // 4 = 7.x **= 2→ Raises current value to power 2 → 7² = 49.
Note: Assignment operators help make your code cleaner and reduce repetition when performing arithmetic and assignment together.