CodeMIRAI
0 XP

Comparison and logical operators

2 min read 5 runnable examples Quiz included

Programs make decisions by asking questions: is the user old enough? Is the password long enough? Each question is a comparison whose answer is True or False.

Comparison operators

OperatorMeaningExampleResult
==equal to5 == 5True
!=not equal to5 != 3True
<less than3 < 5True
>greater than3 > 5False
<=less than or equal5 <= 5True
>=greater than or equal4 >= 5False
Python
age = 17
print(age >= 18)
print(age == 17)
print(age != 17)

Chained comparisons

Python lets you chain comparisons the way you would write them in maths:

Python
temperature = 22
print(18 <= temperature <= 25)     # same as 18 <= t and t <= 25

x = 5
print(1 < x < 10 < 100)

Logical operators

Combine conditions with and, or and not:

OperatorTrue when
a and bboth are true
a or bat least one is true
not aa is false
Python
age = 20
has_ticket = True
is_vip = False

print(age >= 18 and has_ticket)     # both must be true
print(has_ticket or is_vip)         # one is enough
print(not is_vip)

Short-circuit evaluation

Python stops evaluating as soon as it knows the answer. With and, if the left side is false, the right side is never checked:

Python
items = []
# safe: len(items) > 0 is False, so items[0] is never evaluated
print(len(items) > 0 and items[0] == "apple")

Without short-circuiting, items[0] would crash on an empty list. Putting the "safety check" first is a common, useful pattern.

Precedence

not binds tightest, then and, then or. So a or b and c means a or (b and c). Use brackets to make intentions clear:

Python
print(True or False and False)      # True or (False and False)
print((True or False) and False)
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.