← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 7 of 16

Python Relational Operators

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

python
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

python
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

python
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

python
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

python
score = 75
print(0 <= score <= 100)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.