True, false, and good questions.
Turn comparisons and conditions into decisions your code can make.
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.
battery = 82
signal = True
can_launch = battery >= 50 and signal
print(can_launch)
print(not signal)
print(bool(""))True False False
03 Under the hood
- 1
battery >= 50 evaluates to True. signal is also True, so the combined condition is True.
- 2
not reverses truthiness. In this example, not True is False.
- 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 door opens only when has_key is True and locked is False. Write and print the condition.
Reveal one possible solution +
has_key = True
locked = False
print(has_key and not locked)05 Check your signal
Which string is falsy?
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 ↗.