Topic 02

if, elif, else

Hands-on

if is how a program chooses. It asks a question, and only when the answer is True does it run the lines beneath it. Add elif and else, and a program can pick one path out of several, never two. This is the first page where the shape of your code on the screen, its indentation, changes what the program does.

Think of a sorting office. Each letter goes into the first slot whose label matches its address, and into only one slot. Letters that match no label go into the last box, marked "other". That is an if chain exactly.

if and Its Block

An if line is the word if, a question, and a colon. The colon says: the block that belongs to this question starts on the next line. The block is every line below that is indented by four spaces. The first line that is not indented is where the choice ends and the program carries on for everyone.

In the program below, the temperature is 30. The question "is temp greater than 25" answers True, so the indented print runs. The last line is not indented, so it runs whatever the temperature.

weather.py
temp = 30
if temp > 25:
    print("It is hot today.")
print("Have a good day.")
Output
It is hot today.
Have a good day.

Indentation Is Grammar

In many languages indentation is a matter of taste. In Python it is part of the grammar: it is how Python knows which lines belong to the if. Use four spaces, the same four every time. Get it wrong and Python refuses to run the file. The program below forgot to indent the line under the if. The message says an indented block was expected after the if statement on line 2.

no_indent.py
temp = 30
if temp > 25:
print("It is hot today.")
Output
  File "/Users/you/python-course/no_indent.py", line 3
    print("It is hot today.")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

else

else gives the other path: what to do when the answer was False. It has no question of its own and ends with a colon. Exactly one of the two blocks runs, never both and never neither.

else.py
temp = 12
if temp > 25:
    print("It is hot today.")
else:
    print("Take a jacket.")
Output
Take a jacket.

elif: More Than Two Paths

elif, short for else if, adds more questions to the chain. Python asks them from the top down, and the first one that answers True wins. Its block runs, and every question below it is skipped. That means order matters. In the version below, a score of 95 is checked against 50 first. Ninety-five is at least 50, so the program says pass and never reaches the excellent line.

grade_wrong.py
score = 95
if score >= 50:
    print("Pass")
elif score >= 90:
    print("Excellent")
else:
    print("Try again")
Output
Pass

Put the strictest question first, and the same score is recognised as excellent. Each path now catches only what the ones above it let through.

grade.py
score = 95
if score >= 90:
    print("Excellent")
elif score >= 50:
    print("Pass")
else:
    print("Try again")
Output
Excellent
The chain, checked from the top
score >= 90?→Excellent
otherwise, score >= 50?→Pass
anything else→Try again
Common Confusions
  • "Indentation is just for neatness." In Python it decides which lines belong to the if. Wrong indentation either stops the program or silently changes what it does.
  • "Several elif blocks can run." The first true question wins and the rest are skipped, which is why the strictest question goes first.
  • "else needs its own condition." else catches everything the questions above did not; it takes no condition, only a colon.
  • "I can mix tabs and spaces as long as it looks right." Python counts characters, not looks, and stops with a TabError when a block mixes them. In Notepad or TextEdit, press the space bar four times rather than Tab; the code editor in Chapter 12 inserts the spaces for you.
Why It Matters
  • Every rule you can say as "if this, then that, otherwise the other" can now be written directly.
  • Order-of-checks bugs are common in real code. Having seen one in a four-line example, you will spot the next one quickly.

Knowledge Check

In an if, elif, else chain, how many blocks run?

  • Every block whose condition happens to be True
  • Exactly one: the first true branch, or the else
  • Two: the first match, and then the else block after it
  • None, unless every condition in the chain is True

The grading program checks score >= 50 before score >= 90. What does a score of 95 print?

  • Excellent, because 95 is greater than 90
  • Both Pass and Excellent, one line after the other
  • Pass, because the first check that is true wins
  • Try again, because the order of the checks is invalid

What does Python do with a line indented under an if?

  • It treats the indentation as decoration and ignores it
  • It runs that line only when the if's condition is True
  • It runs that line before it checks the if's condition
  • It runs that line twice, once for each possible answer

What does IndentationError: expected an indented block mean?

  • A line was indented further than it should have been
  • The file mixed single quotes with double quotes
  • The if statement was missing its condition
  • A line ending in a colon had nothing indented under it

You got correct