More than two cases
Choose between several paths with a chain of questions. About 8 minutes.
A ladder of questions
A cinema has more than two prices: children under 5 pay nothing, children under 13 pay 50, adults pay 100. Two paths are not enough.
So you add else-if lines, and Python spells that elif. The computer asks the questions from the top. The moment one answer is true, it runs that path and skips the rest of the ladder. The else at the bottom catches everyone nobody else caught.
if age < 5:
price = 0
elif age < 13:
price = 50
else:
price = 100- age
- 30
Is 30 below 5? No, so this path is skipped and the computer moves down.
Mind the order
Because the first yes wins, the order of the questions matters. Say you grade marks like this: ask if the score is at least 50 first, and then if it is at least 75.
A score of 90 is at least 50, so the first path runs and the computer never gets to the second question. Put the strictest question first, and then work down to the loosest. Think about the ladder from the top rung.
if score >= 75:
grade = "B"
elif score >= 50:
grade = "C"The code is: if score >= 90 then grade A, else if score >= 75 then B, else if score >= 50 then C, else F. What grade does a score of 80 get?
- AB
- BA
- CC
Show the answer
B. 80 is not at least 90, but it is at least 75, and that is the first yes.
Ticket price
A cinema charges by age. Children under 5 pay 0, children from 5 to 12 pay 50, people from 13 to 59 pay 100, and people aged 60 or more pay 40. Return the price for a given age.
age = 30 → 100
0 ≤ age ≤ 120