Python Relational Operators
In this page:
Equality and Inequality
== checks whether two values are equal and != checks whether they differ; both always return a bool, and it's a common beginner mistake to write = (assignment) where == (comparison) was intended.
Example: Equality and Inequality
print(5 == 5)
print(5 != 3)
Greater Than and Less Than
> and < compare magnitude between two values — numbers compare by value, and the result is always True or False, ready to be used directly inside an if statement's condition.
Example: Greater Than and Less Than
print(7 > 3)
print(2 < 1)
Greater Than or Equal to and Less Than or Equal to
>= and <= behave like > and < but also count equality as satisfying the condition, which matters whenever a boundary value itself should be included in a valid range, like an age cutoff of "18 or older."
Example: Greater Than or Equal to and Less Than or Equal to
age = 18
print(age >= 18)
Comparing Strings
Strings compare lexicographically, meaning character by character using each character's underlying code point — so "apple" < "banana" is True because a comes before b, the same logic a dictionary uses for alphabetical order.
Example: Comparing Strings
print("apple" < "banana")
Chaining Operators
Python allows chained comparisons like 0 <= score <= 100, which reads naturally and is equivalent to writing 0 <= score and score <= 100 — a concise way to check that a value falls within a range without repeating the variable.
Example: Chaining Operators
score = 75
print(0 <= score <= 100)
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators