Menu

Selection (IF)

elif and Branch Order

elif is short for else if. It gives an if statement another condition to test, and it is only tested when every condition written above it was False. One if statement can have several elif branches, so you can choose between many alternatives without writing a separate if statement for each one.

Only the first True branch runs

Python works down the chain of branches and stops at the first one whose condition is True. That branch's block runs, and every branch below it is skipped โ€” even the ones whose conditions would also have been True.

temperature = int(input("Temperature: "))
if temperature >= 30:
    print("Hot")
elif temperature >= 20:
    print("Warm")
elif temperature >= 10:
    print("Cool")
else:
    print("Cold")

Output when the user types 22:

Temperature: 22
Warm

If you enter 22, the test temperature >= 20 is True, so "Warm" is printed. The test temperature >= 10 would also be True, but it is never reached, because the chain has already finished.

The order of the branches decides the answer

Conditions are checked in the order you write them, so when more than one could be true, the branch written first wins. In the program below the tests overlap and the branches are in the wrong order, so the messages depend on that order rather than on the values:

points = int(input("Points: "))
if points > 0:
    print("Scored")
elif points > 50:
    print("High score")
else:
    print("No score")

Output when the user types 80:

Points: 80
Scored

An entry of 80 matches points > 0 first, so "Scored" prints and the points > 50 branch never runs. Swap those two branches round and the same entry would print "High score" instead. When tests overlap, put the narrowest, most specific test first.

Flowchart of the points program: points > 0 is tested first, then points > 50. An input of 80 prints Scored at the first test, so the High score branch never runs.

Rules for building the chain

  • if comes first; it is the only branch that is always tested.
  • Any number of elif branches follow, each with its own condition.
  • else comes last, carries no condition, and you can write it only once.
  • An elif written after an else is an error: the else has already caught everything that was left, so Python rejects the code.

Every condition line ends with a colon, and the block underneath is indented so Python knows which statements belong to which branch.

Practise this