← Core Concepts
Concept
Comparison operators — ==, !=, <, >, <=, >=
Compare values and get True or False.
Equality operators
# == (equal to):
print(5 == 5) # True
print(5 == 3) # False
# != (not equal to):
print(5 != 3) # True
print(5 != 5) # False
# is vs ==:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (same values)
print(a is b) # False (different objects)
Comparison operators
# < (less than):
print(3 < 5) # True
# > (greater than):
print(5 > 3) # True
# <= (less than or equal):
print(5 <= 5) # True
print(3 <= 5) # True
# >= (greater than or equal):
print(5 >= 5) # True
print(7 >= 5) # True
Chained comparisons
age = 25
# Python allows chaining:
if 18 <= age <= 65:
print("Working age")
# Equivalent to:
if age >= 18 and age <= 65:
print("Working age")
String comparison
# Strings compared lexicographically (alphabetically):
print("apple" < "banana") # True
print("zebra" > "apple") # True
# Case matters:
print("Apple" < "apple") # True (uppercase < lowercase in ASCII)
Common mistakes
# Wrong: = is assignment, not comparison
# if x = 5: # SyntaxError
# Right: == is comparison
if x == 5:
pass
# is vs == for None:
x = None
if x is None: # Preferred for None
pass
if x == None: # Works but not preferred