Conditionals: if, elif, else & match
Branching, truthiness, combining conditions, guard clauses, the ternary expression and pattern matching.
Programs become useful when they can make decisions: show an error when a password is too short, give a discount to members, route a command to the right handler. In Python, decisions are written with if, elif and else — and, since Python 3.10, the powerful match statement.
if, elif, else#
How it works:
- Python checks each condition top to bottom and runs the first block whose condition is true — then skips the rest.
elif("else if") can appear any number of times;elseis optional and must come last.- Each condition ends with a colon, and the block below it is indented.
Order matters. If the >= 60 check came first, a score of 95 would get a "C", because that condition would match before the others were even checked.
Truthy and falsy values#
A condition doesn't have to be a literal True/False. Python evaluates any value for truthiness:
This lets you write natural checks:
Combining conditions#
Use and, or and not, and chain comparisons like in maths:
and binds tighter than or, so a or b and c means a or (b and c). Add parentheses whenever you mix them.
== vs is, and membership with in
== asks "are these equal?". is asks "are these the same object?". Use is only for singletons like None:
Nested conditions and guard clauses#
You can put an if inside another if, but deep nesting quickly becomes hard to read:
A cleaner style is guard clauses: handle the failure cases first and return early, leaving the happy path unindented.
The conditional expression (ternary)#
For choosing between two values, Python has a one-line form: A if condition else B.
Use it for simple value choices only; don't nest them.
Structural pattern matching: match#
match compares a value against a series of patterns. For simple values it reads like a switch statement:
Unlike a C/Java switch, there's no fall-through and no break needed — only the first matching case runs.
match really shines when you destructure data. Patterns can match the shape of sequences and dictionaries and capture parts into variables:
Dictionary patterns and guards (an extra if on a case) make it great for handling JSON-like data:
Note that dictionary patterns match as long as the listed keys are present — extra keys like "shift" are ignored.
Use if/elif for ranges and general boolean logic; use match when you're checking one value against several shapes or constants.
Worked example: a BMI classifier#
Because the conditions are checked in order, each elif only needs the upper bound — the lower bound is implied by the earlier checks failing.
Common mistakes#
- Using
=instead of==in a condition — Python raises aSyntaxError. - Forgetting the colon after
if,elif,elseorcase. - Writing
if x == "a" or "b":— this is always true, because"b"on its own is truthy. Writeif x in ("a", "b"):. - Comparing to
True:if is_ready == True:works but is unidiomatic; writeif is_ready:. - Treating a bare name in a
caseas a constant.case limit:doesn't compare with a variable calledlimit— it captures anything into a new namelimit. Use literals, dotted names (Color.RED) or a guard instead.
What's next#
Your programs can now choose. Next they'll learn to repeat: for and while loops, range, enumerate, zip and friends.
Check your understanding
Quick quiz
1.Which branch runs when no
if/elifcondition is true?2.Which of these values is truthy?
3.In a
matchstatement, what doescase _:do?
Finished reading?
Mark this lesson complete to track your progress.