Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 2 · Lesson 3 · Core

elif, and, or and not: handling several cases

Choose between three or more paths with elif and join conditions with and, or and not.

  • 50 minutes
  • Serves O3
  • Assumes M2.L2

Phase 1: Prepare

Step 1 Warm-up recall

From M2.L2: what does else run on?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • write an if, elif, else chain (Foundation);
  • combine conditions with and, or and not (Core);
  • explain why the order of checks matters (Core).

Phase 2: Teach

Step 3 A familiar example

A grade report checks the highest band first: 80 or more is an A, otherwise 60 or more is a B, otherwise a C. The first match decides.

Step 4 Clear explanation

When there are more than two cases, add elif (else if) between if and else. Python checks from the top and runs only the first block whose condition is True.

score = 72
if score >= 80:
    print("A")
elif score >= 60:
    print("B")
else:
    print("C")
B
score >= 80: False0score >= 60: True, print B1else: skipped2First True wins
With elif the checks run from the top and stop at the first True, so the order of the checks matters.

Order matters. If you checked score >= 60 first, a score of 85 would print B, because the first True wins. Check the narrowest or highest case first.

You can also join conditions:

ExpressionMeaningResult when a is True and b is False
a and bboth must be TrueFalse
a or bat least one is TrueTrue
not areverses the answerFalse

For example, if age >= 13 and age <= 19: is True only for ages 13 to 19.

Step 5 Worked example (4 marks)

What does this print when n = 15? if n > 20: print("big") elif n > 10: print("medium") else: print("small")

  1. 15 > 20 is False. (1 mark)
  2. 15 > 10 is True, so the elif block runs. (1 mark)
  3. The else block is skipped. (1 mark)
  4. Answer: medium. (1 mark)

Go deeper: the professor's notes

Several cases need several conditions in the right order, and each flag must mean one thing.
elif

Next case.

and

Both true.

Order

First True wins.

Case 1ifCase 2elifRestelseCheckeach path
Cases

Flag

FlagMeaning
modeone meaning only

At work: A route flag

One flag chooses between two routines.

  1. Name each flag clearly.
  2. Test each value of the flag.

What a careful practitioner decides. Give each flag one meaning and test every value.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. In an if, elif, else chain Python runs:

2. The value of True and False is:

3. The value of True or False is:

4. The value of not True is:

Phase 4: Close

Step 7 Recap

  • elif adds more cases; the first True block runs.
  • The order of checks changes the result.
  • and, or and not combine conditions.

Step 8 Exit ticket (ungraded)

Write a condition that is True only when age is from 13 to 19 inclusive.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a grade program with four bands: A, B, C and F.

In industry: Knight Capital: a flag that picked old code

On 1 August 2012 Knight Capital repurposed a flag that had once switched on an old function. On one server the old code was still present, so orders with the flag ran the old function. In the first 45 minutes it sent more than 4 million orders to fill 212 customer orders, and the firm lost about 440 million dollars.

Link to this lesson. A condition decides which code runs. If the condition means something different on different machines, the program does the wrong thing at scale.

Source: SEC press release 2013-222; Fortune, 2 Aug 2012; Wikipedia, Knight Capital Group

Common mistakes

MistakeWhy it fails
Checking the wide case firstA score of 85 would match >= 60 and never reach >= 80.
Writing age >= 13 and <= 19Repeat the variable: age >= 13 and age <= 19.
Using separate ifs by mistakeSeparate ifs can all run; elif chooses one.

Limits. More advanced forms, such as chained comparisons, exist but are not needed here.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · Why does the order of elif checks matter?
80check first60thenRestelse
Order

Because the first True wins. If you check score >= 60 before score >= 80, a score of 85 gets the 60 band. Put the narrowest or highest case first.

Card 2 of 3 · How do and, or and not work?
andbothoreithernotreverse
Logic

and needs both sides True; or needs at least one; not reverses. For example, a discount for members who spend over 50 uses and.

Card 3 of 3 · How do you write a condition for a range, such as ages 13 to 19?
Lowage >= 13AndjoinHighage <= 19
Range

Repeat the variable: age >= 13 and age <= 19. Writing age >= 13 and <= 19 is an error. Range checks are common in form validation.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards