Comparison Operators

3 min read ·

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 (==)


Not Equal To (!=)


Greater Than (>)


Less Than (<)


Greater Than or Equal To (>=)


Less Than or Equal To (<=)


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

This is equivalent to:

Examples of Chained Comparisons


Real-World Example (Range Check)


Chaining with Different Operators

You can mix different comparison operators.

Chaining vs Logical Operators

Using Chaining (Recommended)

Using and

Both give the same result, but chaining is cleaner.

Tricky Chaining Example (Interview)


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 ❌

This is valid syntax, but often confusing. Avoid over-complicated chaining.

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