πŸ“ 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 πŸ“‹

OperatorMeaningExample
=Simple assignmentx = 5
+=Add & assignx += 3 β†’ x = x + 3
-=Subtract & assignx -= 2 β†’ x = x - 2
*=Multiply & assignx *= 4 β†’ x = x * 4
/=Divide & assignx /= 2 β†’ x = x / 2
//=Floor divide & assignx //= 3
%=Modulus & assignx %= 5 β†’ x = x % 5
**=Exponent & assignx **= 2 β†’ x = x ** 2
&=Bitwise AND assignx &= 3
|=Bitwise OR assignx |= 2
^=Bitwise XOR assignx ^= 1
>>=Right shift assignx >>= 1
<<=Left shift assignx <<= 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)   # 8

4. Subtract & Assign (-=) βž–

sub_assign.py

x = 10
x -= 4   # x = x - 4
print(x)   # 6

5. Multiply & Assign (*=) βœ–οΈ

mul_assign.py

x = 6
x *= 2   # x = x * 2
print(x)   # 12

6. Divide & Assign (/=) βž—

Division always results in a float.

div_assign.py

x = 9
x /= 2   # x = x / 2
print(x)  # 4.5

7. Floor Divide & Assign (//=) πŸ”½

floor_div_assign.py

x = 9
x //= 2   # x = x // 2
print(x)   # 4

8. Modulus & Assign (%=) 🧩

mod_assign.py

x = 10
x %= 3   # x = x % 3
print(x)   # 1

9. Exponent & Assign (**=) ⚑

exp_assign.py

x = 4
x **= 2   # x = x ** 2
print(x)   # 16

10. 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! 😊