Python Assignment Operators
In this page:
variable = value
variable += value # also -=, *=, /=, //=, %=, **=
Basic Assignment
The plain = operator binds the name on the left to the value on the right — this is assignment, not mathematical equality, and confusing it with == is one of the most common early Python mistakes.
Example: Basic Assignment
x = 5
print(x)
Add and Subtract Assignment
+= adds a value to a variable and stores the result back in that same variable in one step, so count += 1 is shorthand for count = count + 1; -= does the same for subtraction.
Example: Add and Subtract Assignment
count = 10
count += 1 # same as count = count + 1
print(count)
count -= 2 # same as count = count - 2
print(count)
Multiply and Divide Assignment
*= and /= apply the same "do the operation, then reassign" pattern to multiplication and division, letting you update a running total or scale a value without retyping the variable name twice.
Example: Multiply and Divide Assignment
total = 5
total *= 3 # same as total = total * 3
print(total)
total /= 3 # same as total = total / 3
print(total)
Floor Divide and Modulo Assignment
//= performs floor division and reassigns the result, while %= computes the modulo remainder and reassigns it — both are shorthand forms that come up often when tracking counters or wrapping values within a fixed range.
Example: Floor Divide and Modulo Assignment
n = 17
n //= 5 # floor division: n = n // 5
print(n)
m = 17
m %= 5 # modulo: m = m % 5
print(m)
Exponent and Bitwise Assignment
**= raises a variable to a power and reassigns the result, and bitwise compound operators like &= and |= apply the same shorthand pattern to bit-level operations — all follow the identical "operate then store" logic as +=.
Example: Exponent and Bitwise Assignment
x = 2
x **= 3 # exponent: x = x ** 3
print(x)
flags = 1
flags &= 3 # bitwise AND: flags = flags & 3
print(flags)
- Writing
x =+ 1instead ofx += 1, which just assigns+1tox. - Using
+=on a name that has not been defined yet, e.g.total += 5, which raisesNameError. - Using
+=on a list expecting a copy:b = a; b += [1]mutatesatoo since both names refer to one list.
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators