elif: more than two choices

Making Decisions, lesson 3 of 6

🔀 Making Decisions, lesson 3 of 6

elif: more than two choices

Chain several conditions with elif; the first true one wins.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

When there are more than two options, add elif ("else if") branches. Python checks the conditions from top to bottom and runs only the first block whose condition is True. The final else (optional) catches everything else.

Example

What to wear

Try 30, 18, 17 and -5. Only one line prints each time.

Walkthrough

Which branch runs?

>= 28>= 18>= 8else301817-5True–––
Step 1 of 4

30 >= 28 is True, so T-shirt and shorts prints. Python stops there: the other conditions are never checked.

the branch that runs
never checked

Each row is one value of temp. The columns are the conditions temp >= 28, temp >= 18, temp >= 8 and the else, checked left to right.

Quiz

What does this print?

Exercise

Grade calculator

Set grade from score:

  • 90 or more → "A"
  • 80 or more → "B"
  • 70 or more → "C"
  • anything lower → "F"
Example

Mini program: ride the rollercoaster?

One line per input() call

Try heights of 150, 125 and 100.

Quiz

What does this print?