If we have several possible outcomes but only one of them can happen at a time then we need to tell the program that all these conditions are one single decision.
If you were directing people into a theatre you might say "If you are in Rows A to H go through door 1, else if you are in rows I to P go through door 2, else if you are in rows Q to U go through door 3, else go through door 4"
There is clearly only one outcome for each person who hears this instruction. It is clear that all 4 choices are to be taken as a single decision.
if row in "ABCDEFGH":
print("Please enter through door 1")
elif row in "IJKLMNOP":
print("Please enter through door 2")
elif row in "QRSTU":
print("Please enter through door 3")
else:
print("Please enter through door 4")
Note that we use elif rather than else if. Being lazy coders we want to save as much typing as possible!
We could do the same thing if we were sorting people by height. "If you are over 2 metres go through door A, else if you are over 1.8 metres go through door B, else if you are over 1.6 metres go through door C, else go through door D."
if height > 2:
print("Use door A")
elif height > 1.8:
print("Use door B")
elif height > 1.6:
print("Use door C")
else:
print("Use door D")
Someone who is 1.9m tall is over 1.6m tall but they will already have gone through door B before the announcer has got to that part of the instruction, the same is true for the computer program. Once a true condition is found the rest of the decision making code is skipped.
If we had just used if rather than elif like this:
if height > 2:
print("Use door A")
if height > 1.8:
print("Use door B")
if height > 1.6:
print("Use door C")
else:
print("Use door D")
the program would have treated each if as a separate test and would have printed 'Use door B' and 'Use door C' for a 1.9m tall person because each test is treated as a separate decision by the program rather than one big decision with lots of little parts.
The condition tested at each stage doesn't have to have the same variable each time but it usually does.
We can also test for more than one thing at a time, such as 'if you are a female who is over 1.6m tall' or 'if you are a male who is older than 45 and also over 100kg'. To do this we need to use AND and OR
If...Elif...Else video 1 - A demonstration of a decision stack with several outputs
If...Elif...Else video 2 - And the other way up