Comparison Operators
Compare values to get a True or False result.
Syntax
a == b
a != b
0 < x < 10Comparison operators compare two values and return a Boolean.
| Operator | Meaning |
|---|---|
== | Equal |
!= | Not equal |
> < | Greater / less than |
>= <= | Greater / less or equal |
Python lets you chain comparisons: 0 < x < 10 reads just like maths.
Example
print(5 == 5)
print(5 != 3)
print(3 <= 3)
x = 7
print(0 < x < 10)
# Output:
# True
# True
# True
# TrueWhen 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.
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) # FalseCompare strings
Shows that comparison operators work on strings using lexicographic (dictionary) order.
a = 'apple'
b = 'banana'
print(a == 'apple') # True
print(a < b) # True (alphabetical order)
print(a != b) # TrueComparison in a condition
Uses >= comparisons inside if/elif to assign a letter grade based on a numeric score.
score = 85
if score >= 90:
grade = 'A'
elif score >= 70:
grade = 'B'
else:
grade = 'C'
print(grade) # B
Discussion