Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ The essentials
EXPERIMENT 06 / 101

True, false, and good questions.

Turn comparisons and conditions into decisions your code can make.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

01 The idea

Boolean values are True and False. Comparisons such as ==, !=, <, and >= answer questions about values. Combine conditions with and, or, and not. Empty containers, numeric zero, None, and empty strings are falsy; most other values are truthy.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

booleans.py
battery = 82
signal = True

can_launch = battery >= 50 and signal
print(can_launch)
print(not signal)
print(bool(""))
↳ EXPECTED OUTPUT
True
False
False

03 Under the hood

  1. 1

    battery >= 50 evaluates to True. signal is also True, so the combined condition is True.

  2. 2

    not reverses truthiness. In this example, not True is False.

  3. 3

    bool() converts a value to its truth value. An empty string is falsy, but a nonempty string such as "False" is truthy.

04 Your turn, builder

A SMALL MISSION

A door opens only when has_key is True and locked is False. Write and print the condition.

Reveal one possible solution +
one_possible_solution.py
has_key = True
locked = False
print(has_key and not locked)

05 Check your signal

QUICK SIGNAL CHECK

Which string is falsy?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.