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

Python Relational Operators

Relational operators compare two things, like asking whether one kid is taller than another. The answer is always True or False.
Syntax
python
result = a == b  # also !=, >, <, >=, <=

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)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using = instead of == in a condition, as in if x = 5:, which is a SyntaxError.
  2. Comparing a string with a number like "5" == 5, which is False because the types differ.
  3. Comparing strings and expecting numeric order: "10" < "9" is True because strings compare character by character.

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.