Python Arena
Step 3 of 4

The order of conditions

Python checks the branches of a conditional statement from top to bottom and runs only the first one whose condition is true. That makes the order of the conditions important. This program should praise a great result, but it never does:

points = 95
if points >= 50:
    print("Passed")
elif points >= 90:
    print("Passed with distinction")
else:
    print("Failed")
Output
Passed

95 is at least 50, so the first branch runs and the rest of the statement is skipped. In fact the elif points >= 90 branch can never run: every number that is 90 or more is also 50 or more, so the first condition always catches it first. The fix is to check the stricter condition first:

points = 95
if points >= 90:
    print("Passed with distinction")
elif points >= 50:
    print("Passed")
else:
    print("Failed")
Output
Passed with distinction

A good rule for limits like these: with >= or >, check the limits from the highest down; with <= or <, from the lowest up.

Each branch knows what came before

When Python gets to elif points >= 50, it already knows that points >= 90 was false. So that branch is really for points from 50 to 89, without having to say so. You don't need to repeat the earlier conditions in the later ones.

One statement or several

A chain of if, elif and else is one statement, and at most one of its branches runs. Separate if statements are each checked on their own, so several of them can run:

speed = 85
if speed > 80:
    print("Fine: 200 euros")
if speed > 60:
    print("Fine: 100 euros")
Output
Fine: 200 euros
Fine: 100 euros

The driver gets two fines. Change the second if into elif, and only the first one is printed. Use separate if statements when the checks have nothing to do with each other, and one chain when exactly one of the results should come out.

Your task

Challenge 1 of 3

Children under 7 get in free, but this program gives a 5-year-old a youth ticket. Fix the order of the conditions:

Age: 5
Free entry

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Write a program that asks for the wind speed in meters per second (a whole number) and describes it:

  • below 1: Calm
  • 1 to 5: Light breeze
  • 6 to 10: Moderate wind
  • 11 to 17: Strong wind
  • 18 or more: Storm
Wind speed: 8
Moderate wind