π Python Assignment Operators β Updating & Managing Variables
Introduction π
Assignment operators in Python are used to assign values to variables. They can also be used to update variables quickly by combining assignment with arithmetic or bitwise operations.
Note
π‘ Assignment operators help you write cleaner, shorter, and more efficient code.
1. List of Assignment Operators π
| Operator | Meaning | Example |
|---|---|---|
| = | Simple assignment | x = 5 |
| += | Add & assign | x += 3 β x = x + 3 |
| -= | Subtract & assign | x -= 2 β x = x - 2 |
| *= | Multiply & assign | x *= 4 β x = x * 4 |
| /= | Divide & assign | x /= 2 β x = x / 2 |
| //= | Floor divide & assign | x //= 3 |
| %= | Modulus & assign | x %= 5 β x = x % 5 |
| **= | Exponent & assign | x **= 2 β x = x ** 2 |
| &= | Bitwise AND assign | x &= 3 |
| |= | Bitwise OR assign | x |= 2 |
| ^= | Bitwise XOR assign | x ^= 1 |
| >>= | Right shift assign | x >>= 1 |
| <<= | Left shift assign | x <<= 1 |
2. Basic Assignment (=) βοΈ
basic_assignment.py
x = 10
y = 20
name = "Sathish"
print(x, y, name)3. Add & Assign (+=) β
add_assign.py
x = 5
x += 3 # x = x + 3
print(x) # 84. Subtract & Assign (-=) β
sub_assign.py
x = 10
x -= 4 # x = x - 4
print(x) # 65. Multiply & Assign (*=) βοΈ
mul_assign.py
x = 6
x *= 2 # x = x * 2
print(x) # 126. Divide & Assign (/=) β
Division always results in a float.
div_assign.py
x = 9
x /= 2 # x = x / 2
print(x) # 4.57. Floor Divide & Assign (//=) π½
floor_div_assign.py
x = 9
x //= 2 # x = x // 2
print(x) # 48. Modulus & Assign (%=) π§©
mod_assign.py
x = 10
x %= 3 # x = x % 3
print(x) # 19. Exponent & Assign (**=) β‘
exp_assign.py
x = 4
x **= 2 # x = x ** 2
print(x) # 1610. Bitwise Assignment Operators π§
&= (AND assign)
and_assign.py
x = 6 # 110
x &= 3 # 011 -> 010 = 2
print(x)|= (OR assign)
or_assign.py
x = 4 # 100
x |= 1 # 001 -> 101 = 5
print(x)^= (XOR assign)
xor_assign.py
x = 5 # 101
x ^= 1 # 001 -> 100 = 4
print(x)>>= (Right shift assign)
right_shift.py
x = 8 # 1000
x >>= 2 # shift right β 0010 = 2
print(x)<<= (Left shift assign)
left_shift.py
x = 3 # 0011
x <<= 1 # shift left β 0110 = 6
print(x)11. Real-World Example π
real_world.py
total = 0
price = float(input("Enter product price: "))
qty = int(input("Enter quantity: "))
total += price * qty
print(f"Total amount: Rs.{total:.2f}")Conclusion π
>>βAssignment operators help you update variables efficiently β small symbols, big power.β π₯
You now understand all assignment operators in Python. Want the next topic? Try Comparison Operators, Logical Operators, Bitwise Operators, Expressions, or Conditional Statements. Just tell me! π