Comparison Operators

Comparison operators are used to compare two values. They return a Boolean value: True or False.
These operators are heavily used in conditions, loops, validations, and logic building.

Types of Comparison Operators

OperatorDescription
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Equal To (==)

python
print(10 == 10)
python
print(10 == 5)
python
print("Python" == "Python")

Not Equal To (!=)

python
print(10 != 5)
python
print("Python" != "Java")
python
print(5 != 5)

Greater Than (>)

python
print(10 > 5)
python
print(3 > 7)
python
print(7.5 > 5.2)

Less Than (<)

python
print(5 < 10)
python
print(10 < 3)
python
print(2.5 < 3.1)

Greater Than or Equal To (>=)

python
print(10 >= 10)
python
print(8 >= 5)
python
print(3 >= 7)

Less Than or Equal To (<=)

python
print(5 <= 5)
python
print(4 <= 6)
python
print(9 <= 3)

Chaining Comparison Operators

Python allows you to chain comparison operators in a single expression. This makes conditions cleaner, more readable, and more Pythonic.

Basic Syntax

python
a < b < c
This is equivalent to:
python
a < b and b < c

Examples of Chained Comparisons

python
x = 10
print(5 < x < 15)
python
print(1 < 2 < 3)
python
print(10 > 5 > 2)

Real-World Example (Range Check)

python
age = 18
print(18 <= age <= 60)
python
marks = 75
print(60 <= marks <= 100)
python
temperature = 25
print(20 < temperature < 30)

Chaining with Different Operators

You can mix different comparison operators.
python
x = 10
print(5 < x <= 10)
python
print(10 >= x > 5)
python
print(3 < x != 15)

Chaining vs Logical Operators

Using Chaining (Recommended)

python
print(10 < 20 < 30)

Using and

python
print(10 < 20 and 20 < 30)
Both give the same result, but chaining is cleaner.

Tricky Chaining Example (Interview)

python
print(5 < 10 > 3)
python
print(5 == 5 == 5)
python
print(5 < 10 < 3)
python
print(5 < 10 == 10)

Important Rules of Chaining

  • Python evaluates chained comparisons left to right
  • The middle value is evaluated only once
  • All comparisons must be True for the result to be True

Common Mistake ❌

python
print(5 < 10 > 3 < 1)
This is valid syntax, but often confusing. Avoid over-complicated chaining.

Summary

  • Comparison operators compare values
  • They return Boolean results
  • Python supports chaining comparisons
  • Chaining improves readability
  • Equivalent to using and
  • Best for range checks

Practice

  • Check if a number lies between 1 and 100
  • Validate age using chained comparison
  • Predict output of mixed chained expressions
  • Rewrite a chained comparison using and