Table of Contents

# 6 | Understanding Comparison Operators in Python

Python 2026-03-30

Comparison Operators in Python

Introduction

Comparison operators are used in Python to compare two values. They are essential for decision-making in programs, such as checking conditions, controlling flow, and building logic-based applications.

These operators always return a boolean value: True or False, depending on whether the condition is satisfied.

What are Comparison Operators?

Comparison operators are symbols that compare two variables or values. They are commonly used in conditions like if statements, loops, and logical expressions.

Types of Comparison Operators

1. Equal to (==)

Checks if two values are equal.

a = 10
b = 10
print(a == b)   # True

2. Not Equal to (!=)

Checks if two values are not equal.

print(a != b)   # False

3. Greater than (>)

Checks if left value is greater than right value.

print(a > 5)    # True

4. Less than (<)

Checks if left value is less than right value.

print(a < 20)   # True

5. Greater than or Equal to (>=)

Checks if left value is greater than or equal to right value.

print(a >= 10)  # True

6. Less than or Equal to (<=)

Checks if left value is less than or equal to right value.

print(a <= 5)   # False

Using Comparison Operators with Strings

Comparison operators can also be used with strings. Python compares them based on alphabetical (ASCII/Unicode) order.

print("apple" == "apple")   # True
print("apple" > "banana")   # False

Using Comparison Operators with User Input

You can combine comparison operators with user input to make decisions in your program.

age = int(input("Enter your age: "))

print(age >= 18)

Chaining Comparison Operators

Python allows chaining multiple comparisons in a single line.

x = 10
print(5 < x < 20)   # True

Common Mistakes

  • Using = instead of == for comparison
  • Comparing different data types incorrectly
  • Forgetting to convert input values
# Wrong
if x = 10:

# Correct
if x == 10:

Why Comparison Operators are Important?

  • Used in decision-making (if-else conditions)
  • Help control program flow
  • Essential for loops and logic building
  • Used in real-world applications and validations

Best Practices

  • Always use == for comparison, not =
  • Ensure correct data types before comparing
  • Keep conditions simple and readable
  • Use meaningful variable names in comparisons

Conclusion

Comparison operators are essential for building logical conditions in Python. By mastering them, you can create programs that make decisions and respond intelligently to different inputs.