Skip to content
CodeNest

Control FlowLesson 5 of 1912 min

Booleans and Comparisons

Ask yes/no questions about your data and combine the answers with and, or, and not.

By the end you will be able to

  • Compare values with ==, !=, <, >, <=, >=
  • Combine conditions using and, or, not
  • Predict which values Python treats as falsy

Every decision a program makes comes down to a bool: True or False. Comparison operators produce them.

Python
Output
True
False
True
False
True
— expected output; press Run to execute it yourself

Combining conditions

  • and — True only when both sides are True
  • or — True when at least one side is True
  • not — flips a bool
Python
Output
True
False
False
True
— expected output; press Run to execute it yourself

Truthiness

Any value can be used where a bool is expected. Python treats a small, memorable set of values as falsy; everything else is truthy.

Falsy: False, 0, 0.0, "" (empty string), [] (empty list), {} (empty dict), None.

This is why if items: reads so naturally — it means "if there are any items".

Python
Output
False True
False True
False True
False
Name is missing
— expected output; press Run to execute it yourself

Exercise

Write a function can_vote(age, is_citizen) that returns True only when the person is at least 18 and a citizen.

Python
Output

Press Run to execute this code.

Check your understanding

0/2 answered
  1. 1.What does not (5 > 3) evaluate to?
  2. 2.Which of these is truthy?