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?

Add Comment
1 Answer(s)

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:

  • x is assigned the value 10
  • name is 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:

  • True if values are equal
  • False if 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.

Brong Answered 6 days ago.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.