Assignment Operators
We already know the basic assignment operator (=). Assignment operators allow us to perform an arithmetic operation and assign the result back to the same variable in a single, compact step.
| Operator | Example | Equivalent to |
|---|---|---|
+= | x += 5 | x = x + 5 |
-= | x -= 2 | x = x - 2 |
*= | x *= 3 | x = x * 3 |
/= | x /= 4 | x = x / 4 |
%= | x %= 3 | x = x % 3 |
**= | x **= 2 | x = x ** 2 |
Practical Example
python counter = 10
Incrementing
counter += 1 # counter is now 11 print(f'After += 1: {counter}')
Multiplication assignment
price = 50 price *= 1.15 # price = price * 1.15 (adding 15% tax) print(f'Price with tax: {price:.2f}') # Output: 57.50
String concatenation assignment
message = 'Hello' message += ' World' print(message) # Output: Hello World
Using shorthand assignment operators often leads to cleaner, more efficient code, especially in loops.