Conditionals — if/elif/else & match
BeginnerBranching in Python is if/elif/else (there is no switch keyword) — plus structural pattern matching with match/case since Python 3.10 for elegant multi-shape logic.
Overview
Python keeps branching minimal: one if/elif/else construct, truthiness everywhere, and no parentheses required around conditions. Since 3.10, match/case adds structural pattern matching — far more powerful than Java's switch: it destructures tuples, dicts and classes, binds variables, and supports guards. In interviews you'll mostly write clean if/elif ladders; knowing match signals current Python knowledge.
if / elif / else
elif chains replace switch for most cases. Conditions use truthiness — collections are tested directly. Keep nesting shallow: return early instead of nesting deep (guard clauses).
def grade(marks):
if marks >= 90:
return "A"
elif marks >= 75:
return "B"
elif marks >= 40:
return "C"
else:
return "F"
# Guard clauses — flat beats nested
def process(order):
if not order: # empty/None -> reject early
return "no order"
if not order.get("paid"):
return "unpaid"
return f"shipping {order['id']}" # happy path, unindentedmatch/case — Structural Pattern Matching (3.10+)
match compares structure, not just values: it can unpack sequences, match dict keys, bind names, and add if guards. The underscore _ is the wildcard (default).
def handle(command):
match command.split():
case ["go", direction]:
return f"moving {direction}"
case ["pick", *items]: # rest-capture
return f"picking {len(items)} items"
case ["quit" | "exit"]: # OR patterns
return "bye"
case _:
return "unknown command"
print(handle("go north")) # moving north
print(handle("pick pen book")) # picking 2 items
# Matching dict shape (e.g. an API event)
def route(event):
match event:
case {"type": "payment", "amount": amt} if amt > 0:
return f"charge {amt}"
case {"type": "refund"}:
return "refund flow"
case _:
return "ignore"Key Points to Remember
- 1No switch keyword — use elif ladders or match/case (3.10+)
- 2Guard clauses (early returns) keep code flat and readable
- 3match destructures sequences/dicts and binds variables; _ is the default case
- 4Conditions use truthiness — "if data:" covers None AND empty
Interview Questions
Sign in to ask AriaPython has no switch statement — what are the alternatives, including modern ones?
How does match/case differ from a classic switch? Show destructuring with a guard.
Ask Aria about Conditionals — if/elif/else & match
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.