📝 Assignment & Compound Operators
Last Updated: 15th August 2025
📌 What is Assignment (=)?
- The assignment operator
=stores a value into a variable. - It simply places the value on the right into the variable on the left.
Hinglish Tip 🗣: = ka matlab hai “variable ko value dedo” — jaise x = 10 matlab x ke andar 10 daal do.
Example:
x = 10 # x now holds 10
y = 3.5 # y now holds 3.5
📌 Compound Operator
- Compound assignment operators combine an operation and assignment in one step.
- Instead of writing x = x + 5, you can write x += 5.
- They work for arithmetic and bitwise operations (use bitwise versions with integers).
Hinglish Tip 🗣: x += 5 ek chhota shortcut hai x = x + 5 ka.
| Operator | Meaning | Equivalent Long Form |
|---|---|---|
| = | Assign | x = 10 |
| += | Add and assign | x += 5 → x = x + 5 |
| -= | Subtract and assign | x -= 3 → x = x - 3 |
| *= | Multiply and assign | x *= 2 → x = x * 2 |
| /= | Divide and assign (float result) | x /= 4 → x = x / 4 |
| //= | Floor divide and assign | x //= 2 → x = x // 2 |
| %= | Modulus and assign | x %= 3 → x = x % 3 |
| **= | Power and assign | x **= 2 → x = x ** 2 |
| &= | Bitwise AND and assign | x &= 3 → x = x & 3 |
| |= | Bitwise OR and assign | x |= 2 → x = x | 2 |
| ^= | Bitwise XOR and assign | x ^= 4 → x = x ^ 4 |
| <<= | Left shift and assign | x <<= 1 → x = x << 1 |
| >>= | Right shift and assign | x >>= 2 → x = x >> 2 |
Example:
x = 10
x += 5
print(x) # Output: 15
y = 12
y -= 2 # y becomes 10
a = 4
a *= 3 # a becomes 12
b = 20
b /= 4 # b becomes 5.0 (note: division gives float)
💡 Don’t worry! For Bitwise Operator ,We will cover in upcoming section.
💡 Quick Practice
- num = 100 → reduce by 25 using a compound operator (one line).
- x = 4 → multiply by 3 using *= and print.
- val = 50 → divide by 5 using /= and show the type of result.
- m = -9 → do m //= 4 and m %= 4 then print results.
- Exercises