Lesson 29 +10 XP

Comparison Operators

Comparison Operators

Comparison operators compare two values and return True or False.

OperatorNameExample
==Equalx == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater or equalx >= y
<=Less or equalx <= y

Examples

print(5 == 5)   # True
print(5 != 5)   # False
print(5 > 3)    # True
print(5 < 3)    # False
print(5 >= 5)   # True
print(5 <= 4)   # False

Strings compare too

print("a" == "a")   # True
print("a" < "b")    # True (alphabetical order)

One equals vs two equals

  • = assigns a value.
  • == compares values.
x = 5       # assignment
print(x == 5)  # True, comparison

Chained comparisons

Python lets you chain comparisons:

print(1 < 5 < 10)  # True

TL;DR

  • Six comparison operators: ==, !=, >, <, >=, <=.
  • They always return a boolean.
  • Strings compare by alphabetical order.
  • = assigns; == compares.