Python Assignment Operators: Storing & Updating Data
Assignment operators are used to store or update values in variables. While = is the simplest, compound operators allow you to perform math and assignment in a single efficient step.
1. Functional List of Assignment Operators
Assume a = 10 and c = 20 initially for each example:
| Operator | Name | Equivalent To | Result (c) |
|---|---|---|---|
| = | Assignment | c = a | 10 |
| += | Add AND | c = c + a | 30 |
| -= | Subtract AND | c = c - a | 10 |
| *= | Multiply AND | c = c * a | 200 |
| /= | Divide AND | c = c / a | 2.0 |
| %= | Modulus AND | c = c % a | 0 |
| **= | Exponent AND | c = c ** 2 | 400 |
| //= | Floor Div AND | c = c // 3 | 6 |
2. Logic of Compound Operators
Compound operators make your code cleaner and less error-prone. Instead of repeating variable names, you update them in-place.
Example: balance += 500 is much safer than balance = balance + 500 in complex systems because it reduces typo risks.
3. Precedence: The Order of Execution
Assignment operators have very low precedence. This ensures that all calculations on the right side are finished before the variable is updated.
x *= 3 + 1
# Step 1: 3 + 1 = 4
# Step 2: x = x * 4 (5 * 4)
# Result: 20
4. The Walrus Operator (:=)
Introduced in Python 3.8, the Walrus Operator allows you to assign a value inside an expression.
Practice MCQs
1. Which operator finds the remainder and updates the variable?
A) /= | B) %= | C) //= | D) *=
2. If x = 5, what is the value of x after x *= 3 + 1?
A) 16 | B) 20 | C) 15 | D) 8
3. Why is assignment precedence low?
A) To run faster | B) To finish right-side math first | C) To save memory