Comparison Operators

Compare values to get a True or False result.

Syntaxa == b a != b 0 < x < 10

Comparison operators compare two values and return a Boolean.

OperatorMeaning
==Equal
!=Not equal
> <Greater / less than
>= <=Greater / less or equal

Python lets you chain comparisons: 0 < x < 10 reads just like maths.

Example

Example · python
print(5 == 5)
print(5 != 3)
print(3 <= 3)
x = 7
print(0 < x < 10)

# Output:
# True
# True
# True
# True

When to use it

  • A login system checks if the entered password matches the stored hash using ==.
  • An age-gating feature uses >= to determine whether a user is old enough to access content.
  • A sorting algorithm uses < and > to compare values when determining their order.

More examples

Basic comparison operators

Demonstrates all six comparison operators, each returning a boolean True or False.

Example · python
x = 10
print(x == 10)   # True
print(x != 5)    # True
print(x > 8)     # True
print(x < 8)     # False
print(x >= 10)   # True
print(x <= 9)    # False

Compare strings

Shows that comparison operators work on strings using lexicographic (dictionary) order.

Example · python
a = 'apple'
b = 'banana'
print(a == 'apple')  # True
print(a < b)         # True  (alphabetical order)
print(a != b)        # True

Comparison in a condition

Uses >= comparisons inside if/elif to assign a letter grade based on a numeric score.

Example · python
score = 85
if score >= 90:
    grade = 'A'
elif score >= 70:
    grade = 'B'
else:
    grade = 'C'
print(grade)  # B

Discussion

  • Be the first to comment on this lesson.