4. Comparisons

Comparison operators compare two values and produce a boolean (True or False):

OperatorMeaning
>greater than
<less than
>=greater than or equal to
<=less than or equal to
==equal to
!=not equal to

The operands can be expressions, not only literals:

The left side is evaluated first (2 + 2 is 4), and then it is compared with 4.

Comparisons can be chained. a < b < c is shorthand for a < b and b < c:

Chained comparisons are useful for checking that a value is inside a range:

Strings are compared character by character using their Unicode order, so "apple" comes before "banana" and uppercase letters come before lowercase letters.

Coming from JavaScript? Comparisons can be chained: 18 <= age < 65 works in Python, while JS evaluates it left to right and gives a different result.

#01

Compare two expressions

Compare the expression 2 + 2 with 4 using the equality operator (==), and print the result. The left side is evaluated before the comparison.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Compare strings

Use the less-than operator (<) to compare "apple" and "banana", and print the result. Strings are compared character by character using their Unicode order.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Chain two comparisons

Use a single chained comparison with two < operators to check that 1 is less than 2 and 2 is less than 3. Print the result.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Check a range

Store 20 in a variable named age. Use one chained comparison to check that age is at least 18 and less than 65, then print the result.

Print exactly:

Create a free account to save your progress and unlock chapter 2.