DSA Factory
Free lessonsProgramming basics · Stage 2 · Making decisions · Step 2

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.

The first yes wins, and the rest of the ladder is skipped.
In code
if age < 5:
    price = 0
elif age < 13:
    price = 50
else:
    price = 100
Ticket price for a 30-year-old
age < 5 ?
0
age < 13 ?
1
age < 60 ?
2
else
3
question
age
30

Is 30 below 5? No, so this path is skipped and the computer moves down.

Move 1 of 4

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.

Strictest question first, or the later ones never get a turn.
In code
if score >= 75:
    grade = "B"
elif score >= 50:
    grade = "C"
Quick check

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?

  1. AB
  2. BA
  3. CC
Show the answer

B. 80 is not at least 90, but it is at least 75, and that is the first yes.

Your problem

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.

Example
age = 30 → 100

0 ≤ age ≤ 120

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding