Python - Booleans
Overview
Estimated time: 15–20 minutes
Learn truthiness, boolean operators, and common patterns in conditions.
Learning Objectives
- Use
True
andFalse
; understand truthy and falsy values. - Apply
and
,or
, andnot
correctly 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/or
to return booleans; they return operands. - Using
== None
instead 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
True
for non-empty sequences.