Python Comparision Operators

Introduction Reading Time: 10 min

Table of Contents

Description

Comparison operators are used to compare two values and return a Boolean result: True or False. These operators are essential in making decisions in control flow (e.g., if statements).
Operator Description Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 3 < 5 True
>= Greater than or equal to 5 >= 5 True
<= Less than or equal to 3 <= 5 True

Prerequisites

  • Understanding of data types (especially numbers and booleans).
  • Familiarity with arithmetic and variables in Python.

Examples

Here's a simple program in Python:

a = 10
b = 20

# Equal to
print(a == b)   # False

# Not equal to
print(a != b)   # True

# Greater than
print(a > b)    # False

# Less than
print(a < b)    # True

# Greater than or equal to
print(a >= 10)  # True

# Less than or equal to
print(b <= 15)  # False
      

Real-World Applications

Login systems: Check if password or OTP is correct.

Game logic: Compare scores, health, levels.

Finance apps: Validate if balance is sufficient for withdrawal.

Education portals: Determine pass/fail based on marks.

IoT devices: Trigger alerts if temperature exceeds a threshold.

Where topic Can Be Applied

Conditional programming: if, elif, while loops.

Data filtering: In Pandas, NumPy, and SQL queries.

Form validation: Comparing user inputs.

Machine Learning: Accuracy checks, label comparison.

Automation scripts: Trigger actions based on conditions.

Resources

Topic video source

A comprehensive video

Watch

Python pdf

pdf on topic

Visit

Interview Questions

What is the difference between == and is in Python?

Can we use comparison operators on strings? If yes, how?

What does a != b return?

How does Python handle chained comparisons like 3 < a <= 10?

What’s the result of 10 >= 10?