Comparison Operators in Python

Compare numbers, strings, and other values using simple expressions

What Are Comparison Operators?

Comparison operators compare two values and return a Boolean: True or False.

Comparison Operator Table

Operator Description Example
==Equal to5 == 5 → True
!=Not equal to5 != 3 → True
>Greater than7 > 2 → True
<Less than4 < 6 → True
>=Greater than or equal to5 >= 5 → True
<=Less than or equal to3 <= 4 → True

Examples

x = 10
y = 7

print(x == y)   # False
print(x != y)   # True
print(x > y)    # True
print(x < y)    # False
print(x >= y)   # True
print(x <= y)   # False

Comparing Strings

Strings are compared using lexicographic (dictionary) order.

a = "apple"
b = "banana"

print(a == b)  # False
print(a < b)   # True ('apple' comes before 'banana')

Using in Conditions

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
else:
    print("Grade: C or below")

Best Practices