Lesson · Control Flow
Conditional Statements
45 min readConditional Statements
Conditionals select behavior based on truth values. Good conditional code makes business rules obvious and keeps complex Boolean expressions under control.
Learning goals
- Trace an
if/elif/elsechain for any input and name the branch it selects, and why the others are skipped. - Explain how a condition is evaluated: comparisons, truthiness of non-Boolean values, and short-circuiting in
and/or. - Choose between
>,>=, and equality tests so boundary values land in the branch the rule intends. - Restructure a chain with early exits or a conditional expression and judge which form stays readable.
- Diagnose two classic failures: an
elifmade unreachable by a broader earlier test, and aNameErrorfrom a chain with no matching branch.
Mental model
The chain is a priority list, not a set of independent checks. Python evaluates tests top to bottom, runs the first branch whose condition is truthy, and skips the rest, so moving a branch changes the logic even when every condition is untouched.
Mental model
read it top to bottom
test 1 true? → run this block, skip every later test ↓ false test 2 true? → run this block, skip every later test ↓ false else → run the fallback block
Core idea
An if / elif / else chain is one decision with ordered priorities: the first truthy test wins and later tests never run. Because conditions accept any object through truthiness and stop early through short-circuiting, the exact expression you write determines both which branch runs and which code never executes.
if
if starts a conditional chain: Python evaluates the condition expression and runs the indented block only when the result is truthy. The condition can be any object because Python applies its truthiness rules, and if produces no value of its own; it only decides which statements execute.
elif
elif adds another test that runs only when every earlier condition in the chain was false. The first truthy test wins: its block runs and all remaining tests are skipped, so the order of elif clauses encodes the priority between overlapping rules.
else
else is the chain's unconditional fallback, running only when no if or elif condition was truthy. It carries no test of its own and is optional, which is exactly why a chain without one can leave a name unbound and fail later with NameError.
Nested conditions
Nested conditions place one control structure inside another. They are valid but increase the number of execution paths, so extract functions or use early exits when nesting obscures intent.
Truthiness
Every object can participate in a Boolean context. Objects are normally truthy unless their type defines zero length or explicitly defines false truth behavior.
Conditional expressions
A conditional expression chooses one of two values with x if condition else y. Use it for compact value selection, not for long branches with side effects.
Walkthrough
temperature = 31binds anintandraining = Falsebinds abool; the first testtemperature > 30 and not rainingcompares 31 to 30 and negatesraining, so the condition passes only becauseandreceivesTruefrom both sides.- The
elif raining:test is never reached for these values: when theifcondition is true, Python runs its block and skips the remaining tests, somessagebecomes"hot and dry"and the umbrella branch stays dormant. messageis assigned inside the selected branch and read by the finalprint; if no branch assigned it, theprintwould raiseNameError, which is the job the trailingelseperforms.- Predict before running: which branch runs for
(31, False), and whether changingtemperatureto25withraining = Truelands on theelifor theelse.
Experiments to try
- Run the example with
(temperature, raining)set to(25, True)and then(25, False). Write down the branch you expect each time before checking the printedmessage. - Replace
andwithorin the first condition and find two input pairs where the branch selection changes; explain each flip from short-circuit evaluation. - Delete the
elseblock and run with values that match neither test. Read theNameErrortraceback and explain why the failure happens at theprint, not at the chain. - Rewrite the chain as one conditional expression assigned to
messageand decide at what point further nesting would make the one-liner unreadable.
Common mistakes
- Writing
temperature > 30when the rule includes 30: the boundary value falls into the wrong branch, and only a test at exactly 30 exposes it. - Typing
if raining = True:with one equals sign: Python parses conditions as expressions, so assignment here is aSyntaxErrorand the file never runs. - Ordering overlapping tests badly: Python runs the first truthy branch and skips the rest, so a broad test placed early makes a narrower
elifunreachable and encodes the wrong priority. - Assuming every condition is evaluated:
andstops at the first false operand andorat the first true one, so a function call placed after the deciding operand never executes.
Practice: Easy
- Run the worked example with the three pairs
(31, False),(25, True), and(25, False). State the branch for each pair before running, then compare against the printedmessage. - Pass
temperature = 30through the chain, decide from the rule whether 30 counts as "hot", then change>to>=and confirm which branch the boundary value takes. - In the REPL, check
bool(0),bool(""),bool([]), andbool("False"). Explain what each result means for a condition likeelif raining:that tests truthiness rather than identity.
Practice: Medium
- Wrap the chain in a function
def clothing(temperature, raining): ...that returns the message instead of assigning it, then call it with the four boundary pairs and verify every branch is reachable. - Rewrite the chain as a conditional expression for the two-outcome case, trace which value
temperature = 31, raining = Trueselects, and note where a third outcome forces the expression back into anif/else. - Move the
elif raining:test to the top of the chain and list which input pairs change output. Decide whether the reordering expresses a new rule or a bug.
Practice: Hard
- Build
classify(temperature, raining)that covers low, moderate, and high ranges with explicit boundary values. Write down the expected label for every boundary (for example 0, 10, 30, 31) before implementing, then test each one. - Create a failure lab with two entries: a
SyntaxErrorfrom=in a condition and aNameErrorfrom a chain with no matching branch. For each, say which stage of execution reports it: parsing before any code runs, or evaluation at theprint. - Connect this lesson to lesson 14 (pattern matching): pick one decision from the example that reads better as a
matchstatement and one that stays clearest asif/elif/else, and explain how each form expresses priority between overlapping cases.
Lesson checklist
- I can trace the chain for any
(temperature, raining)pair and name the branch it selects. - I can explain truthiness and short-circuit evaluation well enough to say when later operands never run.
- I can choose between
>and>=for a boundary and justify the branch it puts the boundary value in. - I can restructure a chain with early exits or a conditional expression and say why the result is clearer.
Remember
An `if` / `elif` / `else` chain is an ordered priority list: Python runs the first branch whose condition is truthy and skips every test below it. Conditions rest on truthiness and short-circuit evaluation, so any object can drive a decision and later operands may never execute. Order the tests and pick boundary comparisons deliberately, because both quietly change which branch a new input takes.
Interview angles
What is the main purpose of **if**?+
if starts the chain: Python evaluates its condition and runs the block only when the result is truthy, after which every remaining test is skipped. It produces no value itself; it selects which statements in the chain execute.
What should you pay attention to when using **elif**?+
elif is tested only when all earlier conditions were false, and the first truthy branch wins while the rest are skipped. That makes the order of clauses part of the logic: an overlapping test placed too early makes a later one unreachable.
How does **else** fit into this lesson?+
else runs when no condition in the chain was truthy, giving the chain a guaranteed fallback. In the worked example it is what always binds message; without it, inputs that match no test leave the name unbound and the final print raises NameError.
Why can a correctly written `elif` still never run?+
If an earlier test is broader and matches the same inputs, Python runs that first truthy branch and skips every remaining test in the chain. The later elif is then unreachable, so branch order must encode the intended priority.