Flow controls: Conditions · 2 / 22 Theory

else and elif: several paths

A lone if only acts when the condition is true. To choose between two or more paths you add else and elif.

else: the alternative path

else runs when the condition of the if is False. It never has a condition:

n = int(input())

if n >= 0:
    print("Positive or zero")
else:
    print("Negative")

Exactly one of the two blocks always runs.

elif: more than two paths

elif (short for "else if") adds a new condition that is only evaluated if the previous ones failed:

grade = float(input())

if grade >= 9:
    print("Outstanding")
elif grade >= 7:
    print("Good")
elif grade >= 5:
    print("Pass")
else:
    print("Fail")

Python goes through the conditions from top to bottom and runs the first block whose condition is true; the rest is ignored. With grade = 9.5 it only shows Outstanding, even though it is also >= 7 and >= 5.

The order matters

Since the first true condition wins, you must order from most to least restrictive. This code is wrong:

grade = 9.5
if grade >= 5:
    print("Pass")          # runs whenever it passes
elif grade >= 9:
    print("Outstanding")   # never reached

Rules of the structure

  • An if can have zero or several elif.
  • The else is optional and, if it exists, it always goes last.
  • Each if, elif and else ends in : and its block is indented.

Consecutive ifs versus if/elif

Two separate if statements are both evaluated. With elif, only one runs:

x = 10
if x > 5:
    print("greater than 5")
if x > 8:
    print("greater than 8")   # both lines are shown

if x > 5:
    print("greater than 5")
elif x > 8:
    print("greater than 8")   # only the first one is shown

Practice with Positive and negative and Student grade evaluation.