BBampaa

Lessons › Python

Python lesson

elif

The first test is False, the second is True, so Ship by road is shown. Once one branch runs, the rest are skipped.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

elif adds another test. Python checks each one from the top and runs the first branch that's True:

store = "Abuja"
if store == "Lagos":
    print("Local")
elif store == "Abuja":
    print("Ship by road")
else:
    print("Ship by air")

Output:

Ship by road

Key points

elif ...:Another test, checked only if the ones above were False.
Top to bottomPython stops at the first test that's True.
else:Optional. Runs if none of the tests were True.

You can have as many elif lines as you need, between the if and the else.

Practice

Try each one in your head first, then open the answer.

1. Build the elif line: is revenue over 50?
elif revenue > 50:
2. Build the elif line: is the store Abuja?
elif store == "Abuja":
3. Print Local if store is Lagos, Road if it's Abuja, and Air for anywhere else.
store = "Abuja"
if store == "Lagos":
    print("Local")
elif store == "Abuja":
    print("Road")
else:
    print("Air")
4. Print Bulk if qty is 5 or more, Pair if it's 2 or more, and Single otherwise.
qty = 3
if qty >= 5:
    print("Bulk")
elif qty >= 2:
    print("Pair")
else:
    print("Single")
5. Print Good if rating is 4 or more, OK if it's 3 or more, and Poor otherwise.
rating = 2
if rating >= 4:
    print("Good")
elif rating >= 3:
    print("OK")
else:
    print("Poor")

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed