8 · Decisions with if / elif / else
Branch on any condition, keep nesting shallow, and write one-liners with the ternary expression.
`if/elif/else` routes execution through exactly one branch — Python evaluates the chain top-to-bottom and stops at the first truthy condition.
Without this:
Without branching, every program runs the same path regardless of its input — you can't classify, validate, or react to data.
A Python if statement picks exactly one path through your code. Write conditions as plain boolean expressions — no parentheses needed. Add elif for additional branches, and an optional else catches everything that didn't match.
Python (in browser)
This is the archetypal classification threshold pattern. Each `elif` refines the range; the final `else` is the catch-all.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
When the logic is a simple two-way choice, the conditional expression (ternary) collapses the whole if/else onto one line. The form is value_if_true if condition else value_if_false.
Python (in browser)
Use the ternary for simple cases. If you need more than two branches, stick with `if/elif/else` — readability first.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
Python (in browser)
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
Python 3.10 introduced match/case — structural pattern matching. It shines when you need to dispatch on the shape or type of a value (e.g. routing by model architecture name), but for simple threshold checks if/elif/else remains the idiomatic choice.
Is `1 < 2 < 3` a valid Python expression, and what does it return?
Put it into practice: the Arena challenge has you build a grade classifier using `if/elif/else` with server-side tests.
- `if/elif/else` evaluates top-to-bottom and stops at the first truthy branch — order of conditions matters.
- The ternary `x if cond else y` is a one-line `if/else` expression — keep it for simple two-way choices.
- Prefer early returns and lookup dicts over deeply nested `if` blocks to keep code scannable.
Classification thresholds (`if prob >= 0.5: label = 1`) are the final step of every binary classifier. Early stopping checks use `if val_loss > best_loss: patience_counter += 1`. Model-type dispatch (`if model_type == 'tree': ...`) routes training to the right algorithm.
If you remove it: Without conditionals you can't branch on a predicted probability, stop training early, or validate inputs — your pipeline becomes a straight line that ignores everything the data is telling it.