if, elif, and else¶
~15 min ยท prerequisite: Booleans and comparisons
What you will be able to do¶
- Write an
ifstatement that runs a block of code only when a condition isTrue. - Add
elsefor the case where the condition isFalse, andeliffor further cases. - Explain how indentation decides which lines belong to a block, and fix the error when it is wrong.
The idea¶
An if statement starts with the word if, then a condition, then a colon. The lines below it, indented, form a block. The usual style is four spaces for each level of indentation.
When Python reaches an if statement, it checks the condition. If the condition is True, it runs the block. If the condition is False, it skips the block and continues with the first line that is not indented under the if.
An else block follows an if block and runs when the condition is False. An elif block, short for "else if", adds another condition. Python checks an elif condition only when every condition above it was False.
Python checks the conditions from top to bottom and runs the first block whose condition is True. At most one block in a chain runs. If no condition is True and there is no else, nothing runs.
Think of a row of road signs. Python takes the first road whose sign is true, and never reads the rest.
Worked example¶
temperature = 30
if temperature > 25:
print("Hot")
elif temperature > 15:
print("Mild")
else:
print("Cold")
Line by line, this is what Python does:
temperature = 30stores the integer 30.if temperature > 25:checks the first condition. 30 is greater than 25, so the condition isTrue.print("Hot")is indented under theif, so it is part of that block. It runs and showsHot.- Python does not check the
elifcondition, because theifcondition was alreadyTrue. - The
elseblock is skipped for the same reason.
The output is Hot. If you change temperature to 20, the if condition is False, the elif condition is True, and the output is Mild.
Try it¶
Each block stores its result in a variable and checks it with assert.
number = 150
if number > 100:
label = "big"
elif number > 10:
label = "medium"
else:
label = "small"
assert label == "big"
number = 50
if number > 10:
label = "medium"
elif number > 100:
label = "never checked"
assert label == "medium"
label = "unchanged"
if 1 > 2:
label = "changed"
assert label == "unchanged"
The second part of the last block shows the order of the chain. The value 50 is greater than 10, so the first elif runs and the second one is never checked. The third part shows that an if with no matching condition and no else leaves the variable alone.
Common mistakes¶
-
Forgetting the colon. Writing this line:
gives:
Every
if,elif, andelseline ends with a colon. -
Not indenting the block. The following code stops before it runs:
Indent the line under the
if, usually by four spaces. -
Using two separate
ifstatements where you needelif. Eachifis checked on its own, so both can run. The following check fails:The second
ifis alsoTrue, so it replaces"A"with"B". Useeliffor the second condition. -
Writing
=instead of==in a condition. The lineif score = 90:gives:A condition compares values, so use
==.
Practice¶
- Set
age = 16. Write anifandelsethat setsstatusto"adult"whenageis 18 or more, and to"minor"otherwise. Assert thatstatusis"minor". - Set
is_raining = True. Write anifandelsethat setsplanto"stay in"when it is raining and to"go out"when it is not. Assert thatplanis"stay in". - Set
number = -4. Write anif,elif, andelsethat setssignto"positive","zero", or"negative". Assert thatsignis"negative". - Set
hour = 22. Useif,elif, andelseto setpartto"morning"forhour < 12,"afternoon"forhour < 18,"evening"forhour < 22, and"night"otherwise. Assert thatpartis"night". - Stretch: a year is a leap year when it is divisible by 4 and not by 100, or when it is divisible by 400. Use an
ifandelseto setleaptoTrueorFalseforyear = 2024. Assert thatleapisTrue. Then repeat the check foryear = 1900and assert thatleapisFalse.
Solution
-
python age = 16 if age >= 18: status = "adult" else: status = "minor" assert status == "minor" -
python is_raining = True if is_raining: plan = "stay in" else: plan = "go out" assert plan == "stay in" -
python number = -4 if number > 0: sign = "positive" elif number == 0: sign = "zero" else: sign = "negative" assert sign == "negative" -
python hour = 22 if hour < 12: part = "morning" elif hour < 18: part = "afternoon" elif hour < 22: part = "evening" else: part = "night" assert part == "night" -
```python year = 2024 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: leap = True else: leap = False assert leap
year = 1900 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: leap = True else: leap = False assert not leap ```
The year 1900 is divisible by 100 but not by 400, so it is not a leap year.
Recap¶
- An
ifblock runs when its condition isTrue.elifadds another condition, andelsecovers all remaining cases. - Python checks the branches from top to bottom and runs at most one of them.
- Indentation decides which lines belong to a block. A missing colon or missing indentation is a syntax error.