Python Foundations·Lesson 8 of 67·beginner
Making decisions
if, elif and else — plus indentation, the conditional expression, and the guard-clause pattern that keeps code flat.
In this lesson · 12 min
- →Branch with if, elif and else
- →Understand how indentation defines a block
- →Use conditional expressions for simple choices
- →Flatten nested conditions with guard clauses
Up to now every program has run straight through. if is how a program takes different paths.
Two things define the structure: the colon at the end of the if line, and the
indentation of the lines that follow it.
Indentation is the syntax
Other languages use braces. Python uses indentation, and it is not optional.
Get it wrong and Python tells you immediately:
else and elif
elif chains further tests. Python checks them top to bottom and takes the first one that
is true — the rest are skipped entirely.
Because only the first match runs, the order matters. Try reversing those branches — putting
score >= 60 first — and everything above 60 becomes a D.
Combining conditions
The conditional expression
When a whole if/else exists only to pick between two values, collapse it into one line:
Read it as “this value if condition else that value”. Use it for simple choices only — nesting them gets unreadable fast.
Guard clauses
Nested conditions get hard to follow quickly:
The same logic, flattened by handling each failure and returning immediately:
Same behaviour, one level of indentation, and each rule is visible on its own line. This is called a guard clause, and it is one of the highest-value habits you can build early.
match for dispatching on a value
When you are branching on what something is rather than whether something is true, Python
has match:
case _ is the catch-all. Reach for match when you have several cases on one value; stick
with if/elif otherwise.
Try it yourself
Print one line describing the latency: fast under 50 ms, ok under 200 ms, otherwise slow.
Rewrite the function using guard clauses so it never nests more than one level deep. It must behave identically.
Check yourself
How many of these branches run when score is 95?
Recap
- A colon opens a block; indentation (four spaces) says what is inside it.
elifchains stop at the first true condition, so order the branches carefully.value_a if condition else value_bis the one-line form, for simple choices only.- Guard clauses — check and return early — keep validation code flat and readable.
matchis for dispatching on what a value is, when there are several cases.