Syllabus Lesson 11 of 239 · Control Flow
Control Flow

Boolean Logic: and / or / not

Conditions are booleans: they are either True or False. You can combine them with three words.

  • and is true only when both sides are true.
  • or is true when at least one side is true.
  • not flips a boolean.
logged_in = True
is_admin = False
print(logged_in and is_admin)   # False
print(logged_in or is_admin)    # True
print(not is_admin)             # True

You will often combine these with comparisons. Here a value is "in range" only when both checks pass:

age = 30
allowed = age >= 18 and age <= 65
print(allowed)   # True

Python also lets you chain comparisons, which reads like math. This means exactly the same thing:

age = 30
allowed = 18 <= age <= 65
print(allowed)   # True

Use not to invert a whole check. not (a and b) is true when they are not both true.

Your turn

Define a function can_ride(age, height_cm) that returns True only when the person is at least 12 years old and at least 140 cm tall, otherwise False. Use and (a chained comparison is fine too).

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output