Conditionals are how programs make decisions. Python's if family is short and readable, but the way you structure conditionals separates clean code from spaghetti. This chapter covers both.
if / elif / else
score = 78if score >= 90:grade = "A+"elif score >= 75:grade = "A"elif score >= 60:grade = "B"else:grade = "C"print(grade) # A
Python uses indentation to mark blocks — no curly braces, no then.
Truthy & falsy values
Any value can be tested in an if — Python evaluates "truthiness". The following are all falsy:
| Falsy values |
|---|
| False |
| None |
| 0, 0.0, 0j (any zero) |
| "" (empty string) |
| [], {}, (), set() (empty containers) |
| custom objects with __bool__ → False |
name = ""# Pythonic — relies on truthinessif not name:print("name is missing")# Less pythonic — explicit comparisonif name == "":print("name is missing")# Common pattern — provide defaultdisplay_name = name or "Anonymous"
Ternary expressions
age = 22status = "adult" if age >= 18 else "minor"print(status) # adult# Compose with f-stringsprint(f"You are {'eligible' if age >= 18 else 'too young'} to vote.")
match-case (Python 3.10+)
Python's pattern matching — like a smarter switch. Best for branching on the shape of data.
def describe(point):match point:case (0, 0):return "origin"case (x, 0):return f"on x-axis at {x}"case (0, y):return f"on y-axis at {y}"case (x, y):return f"point at ({x}, {y})"case _:return "not a 2-tuple"print(describe((0, 0))) # originprint(describe((5, 0))) # on x-axis at 5print(describe((3, 4))) # point at (3, 4)
Guard clauses
One of the most underused patterns. Instead of nesting your "happy path" deep inside conditionals, return early:
# ❌ Nesteddef process(user):if user is not None:if user.is_active:if user.has_subscription:return charge(user)else:return Noneelse:return Noneelse:return None# ✅ Guard clauses — return early, indent shallowlydef process(user):if user is None: return Noneif not user.is_active: return Noneif not user.has_subscription: return Nonereturn charge(user)
The second version is faster to read, easier to debug, and gives each failure a clear exit point.
Writing clean conditionals
- Prefer guard clauses over nested
iftrees. - Use
infor membership:if status in {"open", "pending"}:, not a chain ofors. - Extract complex conditions into named variables:
is_eligible = age >= 18 and has_id and not is_banned. - Reach for
match-casewhen matching the shape of data, not for simple value checks. - Avoid double negatives:
if not is_invalid:is harder to read thanif is_valid:.
Key takeaways
- 01Python uses indentation, not braces — and any value can be truthy or falsy.
- 02Always use is None for None checks; never == None.
- 03Ternary expressions are one-liners — break to regular if/else if they wrap.
- 04match-case is for matching the shape of data; if/elif is fine for simple values.
- 05Guard clauses (return early) beat deeply nested ifs every time.
