Comparison Operators
Compare values with ==, !=, <, >, <=, >=
Knowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Comparison operators let you compare values and get a boolean (True or False) result. Every comparison asks a question: "are these equal?", "is this bigger?" — and the answer is always True or False.
Equality: `==`
print(5 == 5)
print(5 == 3)
print("hello" == "hello")== checks if two values are equal. Don't confuse it with = (assignment) — that's a different operator entirely!
Inequality: `!=`
print(5 != 3)
print(5 != 5)!= means "not equal" — the opposite of ==.
Greater / Less than: `>`, `<`, `>=`, `<=`
print(10 > 5) # greater than
print(3 < 7) # less than
print(5 >= 5) # greater than or equal
print(4 <= 4) # less than or equalThese work as you'd expect from math class. > and < are strict; >= and <= include equality.
Chained Comparisons
Python lets you chain comparisons together:
x = 7
print(1 < x < 10)
print(1 < x < 5)1 < x < 10 is shorthand for 1 < x and x < 10. Python evaluates chained comparisons left to right — both conditions must be True.
Comparing Different Types
In Python 3, ordering comparisons (<, >, <=, >=) between incompatible types raise a TypeError:
# print(5 < "hello") # raises TypeErrorHowever, == and != work across types — they return False/True:
print(5 == "5") # False (different types)
print(5 != "hello") # TrueComparison results as values
Every comparison produces a boolean — a value you can store and reuse:
is_adult = age >= 18
if is_adult:
print("Can vote")Examples
Numeric comparisons
Basic comparison operators on numbers
a = 10
b = 20
print(a < b) # True
print(a == b) # False
print(a >= b) # FalseChained comparison
Check if a value falls within a range using chained comparisons
score = 85
print(0 <= score <= 100) # True — score is in rangeStoring comparison results
Comparison results are boolean values you can store in variables
name = "Alice"
is_alice = name == "Alice"
print(is_alice) # TrueHow well did you understand this?
Next in Programming Fundamentals
Logical Operators