Selection (IF)
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.
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
WarmIf 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.
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
ScoredAn 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.
Every condition line ends with a colon, and the block underneath is indented so Python knows which statements belong to which branch.
Edexcel GCSE Computer Science ยท Selection (IF)