Python Fundamentals · Python Basics

Booleans, Comparisons and Logic

True and False, comparison operators, and/or/not, chained comparisons, and which values count as false.

booleans.py

age = 17
has_ticket = True
is_adult = age >= 18
can_enter = is_adult or has_ticket
needs_help = not has_ticket and age < 12
in_range = 13 <= age <= 19          # comparisons can be chained
empty_is_false = bool("")           # empty things count as False
zero_is_false = bool(0)
print(is_adult, can_enter, needs_help, in_range, empty_is_false, zero_is_false)

Step by step

  1. age is created with the value 17.
  2. has_ticket is created with the value true.
  3. 17 >= 18 is False: a comparison always gives True or False.
  4. or is True if either side is: False or True gives True.
  5. not has_ticket is False, so the whole and is False without even checking the age.
  6. A chained comparison: is 13 <= 17 and 17 <= 19? Yes, True.
  7. An empty string counts as False…
  8. …and so does 0. Empty lists, empty dicts and None are false too; almost everything else is true.
  9. Comparisons make booleans; and/or/not combine them; and empty or zero values count as False in conditions.