if - else gives only two paths. But a cinema ticket might be number 1, 2 or 3, each with its own prize. To add another condition use elif, short for "else if": otherwise, if...
ticket = 2
if ticket == 1:
print("Free drink")
elif ticket == 2:
print("Includes popcorn")
elif ticket == 3:
print("Mini snack set")Includes popcorn
Add as many elif lines as you need, then an optional else at the end for every case no condition matched:
ticket = 10
if ticket == 1:
print("Free drink")
elif ticket == 2:
print("Includes popcorn")
else:
print("No prize")No prize
How the chain runs
The computer checks the conditions from top to bottom and stops at the first True one; it runs that block and skips the rest of the chain. So at most one block runs:
cup = 0
if cup <= 10:
print("10 or fewer")
elif cup <= 5:
print("5 or fewer")
elif cup <= 3:
print("3 or fewer")10 or fewer
== 0, then <= 3, then the rest.cup = 2
if cup == 0:
print("We need to go buy some!")
elif cup <= 3:
print("It's almost gone")
else:
print("There is still some")It's almost gone
A chain always starts with one if, and else, if present, comes last. Every elif has a condition; else does not.
Practice
Add at the end: if ticket equals 4, print Goods voucher; if no condition matches, print No prize.
ticket = 10
if ticket == 1:
print("Free drink")
elif ticket == 2:
print("Includes popcorn")
elif ticket == 3:
print("Mini snack set")Press Run to see the result. Assign 3 to people. If people equals 2, print 10% off; if it is 3 or more, print 20% off; otherwise print Regular price.
Press Run to see the result. Complete the elif line: if score is 80 or more, print Pass.
score = 82
if score == 100:
print("Perfect score")
___
print("Pass")Press Run to see the result. Assign 5 to egg. If egg equals 0, print Out of stock; else if it is 3 or less, print Low stock; otherwise print In stock.
Press Run to see the result. Assign 77 to english. If it is 100, print Perfect score; else if it is 75 or more, print Pass; otherwise print Make-up exam.
Press Run to see the result. The program prints C for every mark of 65 or more because the conditions are in the wrong order. Reorder them (A from 85, B from 75, C from 65, otherwise D) so it prints B for a mark of 78.
Hint
Start with the narrowest condition: the highest mark first.mark = 78
if mark >= 65:
print("C")
elif mark >= 75:
print("B")
elif mark >= 85:
print("A")
else:
print("D")Press Run to see the result. Assign 38 to temp. If it is 35 or more, print Very hot: drink water; else if 25 or more, print Nice day; else if 15 or more, print Take a jacket; otherwise print Cold: stay warm.
Press Run to see the result. Key points
- Shape:
if, then any number ofelif condition:, then an optionalelse:at the end. - Conditions are checked from the top, and only the first True one runs.
- Put the narrowest condition first so a wider one does not hide it.