What is the difference between = and == in Python?
Many Python beginners confuse the assignment operator (=) with the comparison operator (==). This often leads to logical errors in conditions and loops.
What is the difference between = and == in Python, when should each one be used, and can you provide simple examples to explain their behavior?
What is the difference between = and == in Python?
In Python, = and == look similar but serve completely different purposes. Confusing them is a common beginner mistake and often leads to logical errors.
✅ = (Assignment Operator)
The = operator is used to assign a value to a variable.
Example:
x = 10
name = "Mohi"
Here:
xis assigned the value10nameis assigned the string"Mohi"
❌ You cannot use = in conditions:
if x = 10: # ❌ SyntaxError
✅ == (Comparison Operator)
The == operator is used to compare two values and check if they are equal.
Example:
x = 10
if x == 10:
print("x is equal to 10")
This comparison returns a Boolean value:
Trueif values are equalFalseif values are not equal
✅ Key differences at a glance
| Operator | Purpose | Returns |
|---|---|---|
= |
Assigns a value | No return value |
== |
Compares two values | True or False |
✅ Real-life example
price = 50 # assignment
price == 50 # comparison
- First line stores the value
- Second line checks the value
⚠️ Common beginner mistake
if age = 18: # ❌ Wrong
Correct:
if age == 18: # ✅ Correct
🔑 Summary
- Use
=to store data - Use
==to compare data - Mixing them causes errors or incorrect logic
Understanding this difference is essential for writing correct Python programs.