Skip to content

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.

PythonPython not started

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.

PythonPython not started

Get it wrong and Python tells you immediately:

PythonPython not started

else and elif

PythonPython not started

elif chains further tests. Python checks them top to bottom and takes the first one that is true — the rest are skipped entirely.

PythonPython not started

Because only the first match runs, the order matters. Try reversing those branches — putting score >= 60 first — and everything above 60 becomes a D.

PythonPython not started

Combining conditions

PythonPython not started

The conditional expression

When a whole if/else exists only to pick between two values, collapse it into one line:

PythonPython not started

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:

PythonPython not started

The same logic, flattened by handling each failure and returning immediately:

PythonPython not started

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:

PythonPython not started

case _ is the catch-all. Reach for match when you have several cases on one value; stick with if/elif otherwise.

Try it yourself

Exercise 1

Print one line describing the latency: fast under 50 ms, ok under 200 ms, otherwise slow.

Your turnPython not started
Exercise 2

Rewrite the function using guard clauses so it never nests more than one level deep. It must behave identically.

Your turnPython not started

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.
  • elif chains stop at the first true condition, so order the branches carefully.
  • value_a if condition else value_b is the one-line form, for simple choices only.
  • Guard clauses — check and return early — keep validation code flat and readable.
  • match is for dispatching on what a value is, when there are several cases.
Next: Repeating work →