CodeBlanks Logo Icon CodeBlanks

Comparison

Learn ==, !=, <, >, <=, >= operators.

Comparison operators

Comparison operators compare two values and return a bool: == equal, != not equal, < less than, > greater than, <= less or equal, >= greater or equal.

print(5 == 5)   # True
print(3 < 7)    # True
print(10 != 10) # False

These operators are used in if conditions. The result is always True or False.

Chained comparison

Python supports chained comparison: 1 < x < 10. This is the same as 1 < x and x < 10 but more readable.

x = 5
print(1 < x < 10)   # True
print(0 <= x <= 5)  # True

This feature is absent in many other languages and is one of Python's readability wins.

Practice Print comparisons

Assign age = 18. Print print(age >= 18) and print(age < 21).

Starter code

main.py
# Do the comparison

Sample solution

main.py
age = 18
print(age >= 18)
print(age < 21)

Expected output

True
True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is 5 != 5?

  • True
  • It raises an error
  • 0
  • False Correct answer

Explanation: Since 5 equals 5, != gives False.

2 Equality check

Question
print(10 ____ 10)
Answer
print(10 == 10)

Explanation: == is the equality comparison.

3 Match the operators

Term Meaning
== Equal
!= Not equal
< Less than
>= Greater or equal

All lessons in Beginner