Table of Contents
Toggle
Python comparison operators are essential building blocks for creating logical workflows in programming. These binary operators evaluate relationships between values, returning Boolean (True/False) results that drive decision-making in:
| Operator | Name | Example | Result |
|---|---|---|---|
== |
Equal To | 5 == 5 |
True |
!= |
Not Equal To | 3 != 2 |
True |
# Chained comparisons
age = 25
print(18 <= age <= 30) # Output: True
# Type-aware comparison
print(1 == True) # Output: True (Due to bool inheritance from int)
print(1 is True) # Output: False (Different object types)
# String lexicographical comparison
print("apple" > "orange") # Output: False (Compares ASCII values)
user_input = 150
MIN_VALUE = 0
MAX_VALUE = 100
if MIN_VALUE <= user_input <= MAX_VALUE:
print("Valid input")
else:
print(f"Input must be between {MIN_VALUE}-{MAX_VALUE}")
def sort_numbers(a, b, c):
if a > b: a, b = b, a
if b > c: b, c = c, b
if a > b: a, b = b, a
return a, b, c
print(sort_numbers(15, 3, 9)) # Output: (3, 9, 15)
# Dangerous direct comparison
print(0.1 + 0.2 == 0.3) # Output: False
# Safe comparison using tolerance
tolerance = 1e-9
print(abs((0.1 + 0.2) - 0.3) < tolerance) # Output: True
a < b < cis for None comparisons