Decisions — if, elif, else

A traffic light is a decision box at a junction. If the lamp is red, vehicles stop. If it is yellow, they wait. Otherwise they go. Your program can choose a path the same way. Without if, a program is a single railway track. With if, it is a set of points — still deterministic, just branched.

Junction traffic light

if / elif / else choose a path.

You will be able to

  • Write a condition that is True or False
  • Use if / elif / else so only one branch runs
  • Indent the body of each branch

A condition is a yes/no question

== asks “is it equal?”. < and > ask less or greater. >= is “at least” (greater or equal) — the line that saves you when marks are exactly 40.

A single = still means store, even inside a messy line. if color = "red" is wrong. if color == "red" is a question. This mix-up is the most common beginner bug in the world; expect to make it once, then never again.

Indentation is not decoration

Python uses spaces at the start of a line to mean “this belongs to the if above”. Other languages use curly braces { }. In Python, the indent is the grouping. Two extra spaces (or a tab) in the wrong place and the story changes.

The line with if ends with a colon :. The next lines that are indented are the “then” recipe. When you un-indent, you have left that branch.

elif means else if — only one winner

Check the most specific case first. Red is not yellow; if you test green first with a sloppy condition you might never reach red. elif chains alternatives. else is the backpack that catches everything left.

At most one branch runs. That is what you want at a junction: not stop and go in the same second.

Pass mark — includes equality

marks = 40
if marks >= 40:
    print("Pass")
else:
    print("Retry")

Words that matter

Condition
An expression that is True or False.
Branch
A block of lines that runs only when its condition matches.
Boolean
The type of True and False.

Common mistakes

Avoid: if color = "red": (one equals).

Do this: if color == "red": (two equals to compare).

Avoid: Forgetting the colon after if.

Do this: if marks >= 40: — colon, then indent.

Example program — Crossing the road

Change color to "green" or "yellow" and Run again. Only one message should appear.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Your turn — Exam result

marks is 72. If marks are 40 or more, print Pass, otherwise print Retry.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Self-assessment

Check your understanding before you mark the lesson complete.

1. How do you test whether color is the text red?
2. Why does if marks >= 40 pass when marks is 40?
3. In an if / elif / else chain, how many branches run?

Progress is stored in a browser cookie on this device.