Contact
Evil Genius SocietyHomeLearnForumLeaderboardSocialsMessages
← Back to module

Lesson 2 of 10

One comparison answers one question. Real programs usually need to combine several — "is the user an adult and do they have a ticket?" That's what logical operators are for.

and

and is True only when both sides are True.

age = 25
has_ticket = True
print(age >= 18 and has_ticket)

or

or is True when at least one side is True.

is_weekend = False
is_holiday = True
print(is_weekend or is_holiday)

not

not flips a boolean to its opposite.

is_raining = False
print(not is_raining)

The truth tables

Worth memorising — these three tables explain every logical expression you will ever write.

print(True and True)
print(True and False)
print(True or False)
print(False or False)
print(not True)

Combining them

You can chain as many as you like. Use parentheses when the order matters — they also make the intent obvious to whoever reads the code next.

age = 30
has_ticket = True
is_banned = False

print(age >= 18 and has_ticket and not is_banned)

Without parentheses, not runs first, then and, then or. When in doubt, add parentheses.

Try it yourself

Given is_weekend = True and is_raining = False, print a good-day-out check (is_weekend and not is_raining), then whether either is true, then the opposite of is_weekend.

Checkpoint

  • and needs both sides true; or needs at least one; not flips the value.
  • Precedence is not, then and, then or.
  • Parentheses cost nothing and make intent clear.

Questions about this lesson

Log in to ask a question.