Python - Booleans
Overview
Estimated time: 15–20 minutes
Learn truthiness, boolean operators, and common patterns in conditions.
Learning Objectives
- Use
TrueandFalse; understand truthy and falsy values. - Apply
and,or, andnotcorrectly with short-circuiting. - Prefer explicit comparisons for clarity (e.g.,
if x is None).
Prerequisites
Truthiness
# Falsy: 0, 0.0, '', [], {}, set(), None, False
# Truthy: most other values
items = []
if not items:
print("No items")
Boolean operators
x, y = 0, 5
print(x and y) # 0 (returns first falsy)
print(x or y) # 5 (returns first truthy)
print(not x) # True
Common Pitfalls
- Expecting
and/orto return booleans; they return operands. - Using
== Noneinstead ofis None.
Checks for Understanding
- What does
[] or 'fallback'evaluate to? - How do you test for
None?
Show answers
'fallback'if x is None:
Exercises
- Use short-circuiting to pick the first non-empty string from three variables.
- Write a predicate that returns
Truefor non-empty sequences.