if, elif and else in Python
Builds on lessons 1 to 5. Start at lesson 1
Learn
if, elif and else
So far every line runs. With if, your program can choose.
temp = 31
if temp > 30 then
print("Hot!")
elseif temp > 15 then
print("Nice.")
else
print("Jacket time.")
endiftemp ← 31
IF temp > 30 THEN
OUTPUT "Hot!"
ELSE IF temp > 15 THEN
OUTPUT "Nice."
ELSE
OUTPUT "Jacket time."
ENDIFtemp = 31
if temp > 30:
print("Hot!")
elif temp > 15:
print("Nice.")
else:
print("Jacket time.")How it works: Python checks the conditions from top to bottom and runs the block under the first one that is true. Then it skips the rest. elif (short for "else if") and else are optional, and you can have as many elifs as you like. So with temp = 31, only "Hot!" prints, even though 31 is also greater than 15.
Two details that matter:
- The line ends with a colon
:. - The code inside is indented (4 spaces is the standard). Indentation is not decoration in Python; it is how Python knows which lines belong to the
if. Get it wrong and you get anIndentationError, or worse, code that runs at the wrong time.
Learn
Comparing and combining
Comparison operators give you True or False:
==equal,!=not equal<><=>=
Classic mistake: = assigns, == compares. if score = 10: is a syntax error.
Combine conditions with and, or and not:
if age >= 13 and age <= 19:
print("teen")Python even lets you write that as 13 <= age <= 19, which reads like maths.
Strings can be compared too: "cat" == "Cat" is False, because case counts. Lowercasing first with .lower() is the usual fix.
GCSE exam boards
- OCR 2.2.1 Programming fundamentals
- AQA 3.2.2 Sequence, selection, iteration, 3.2.4 Comparisons
- Edexcel 6.2.2 Selection and repetition, 6.5.2 Relational operators
Try
Run it: a grade checker
The example is already in the editor. Run it, change one thing, and run it again.
score = 74
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "try again"
print(f"{score} gets {grade}")
answer = "YES"
if answer.lower() == "yes" and score > 50:
print("Both conditions are true")
print(10 == 10, 3 != 3, 5 <= 4)
Practice
Even or odd
Read a whole number. Print even if it is even and odd if it is not. With the input 17 the output is odd.
Your program reads the Input box under the editor.
n = int(input())
print("even")
Practice
Check a rider's height
A ride needs riders to be at least 140 cm tall and under 200 cm. Read a height (whole number). Print You can ride if both rules are met, Too short if the height is under 140, and Too tall otherwise. With the input 200 the output is Too tall.
Your program reads the Input box under the editor.
height = int(input())
if height >= 140:
print("You can ride")
PracticePredict the output
Which branches run?
Type exactly what this prints. There are two separate if statements here.
score = 85
if score > 50:
print("pass")
elif score > 80:
print("merit")
else:
print("fail")
if score > 80:
print("well done")
Break/fixFix the bug
Nobody gets a distinction
Marks of 70 or more should get Distinction, 55 to 69 Merit, 40 to 54 Pass, and anything lower Fail. Every mark of 40 or more comes out as Pass. Fix it.
Milestones
- Distinction
- Merit
- Pass
- Fail
Your program reads the Input box under the editor. Check also tries 3 other inputs.
mark = int(input())
if mark >= 40:
print("Pass")
elif mark >= 70:
print("Distinction")
elif mark >= 55:
print("Merit")
else:
print("Fail")
Practice
Cinema ticket prices
Read an age (whole number), then yes or no for whether the person has a student card. Print the ticket price:
- under 12:
Ticket: 5 - 16 to 25 with a student card:
Ticket: 7 - 65 or over:
Ticket: 6 - anyone else:
Ticket: 10
The check runs five different people through your program.
Milestones
- Child
- Student
- Student card but 30
- Senior
- No card
Your program reads the Input box under the editor. Check also tries 4 other inputs.
age = int(input()) card = input()
Your turn
Judge rock, paper, scissors
Two players type their moves, one per line: rock, paper or scissors. Rock beats scissors, scissors beats paper, paper beats rock. Print Draw, Player 1 wins or Player 2 wins. People type with random capitals and stray spaces, so Rock and rock are the same move.
Milestones
- Rock beats scissors
- Scissors beats paper
- Same move, different typing
- Scissors beats paper again
- Paper beats rock
- Paper beats rock again
On your own. Hints open after your first check.
Your program reads the Input box under the editor. Check also tries 5 other inputs.
Passed
You can now
You have what you need for a project: Character stat card 30 min, Gig door checker 40 min