Lesson 30 +10 XP

Logical Operators

Logical Operators

Logical operators combine boolean values: and, or, and not.

and

True only when BOTH sides are true:

print(5 > 3 and 5 < 10)  # True
print(5 > 3 and 5 > 10)  # False

or

True when AT LEAST ONE side is true:

print(5 > 3 or 5 > 10)   # True
print(5 < 3 or 5 > 10)   # False

not

Flips a boolean:

print(not True)   # False
print(not (5 > 3))# False

A real-world example

age = 25
has_ticket = True
if age >= 18 and has_ticket:
    print("Welcome in!")

Truth table for and

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

TL;DR

  • and needs both true.
  • or needs at least one true.
  • not flips the value.
  • Use them to combine conditions.