runtime
17 / 250
lesson 17 Conditional Logic · beginner

elif and else

elif tries another test. else runs when every test above it was false.

You'll be able to
  • Add an else for the case the if skipped
  • Chain another test with elif
  • Order the tests so the right branch runs first
The idea

An if by itself does nothing when the test is false. else is the branch for that case. It has no test of its own.

elif means "else, if". Python tries it only when the if above was false. Only one of the branches runs: the first one whose test is true.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · else when the count is zero
qty = 0
if qty > 0:
    print("A few")
else:
    print("None yet")
example-2.py · Three labels for a status
status = "packing"
if status == "delivered":
    print("Send")
elif status == "packing":
    print("Wait")
else:
    print("Check")

Order matters with bands. Because the first true test wins, check the strictest band first. With a score of 95, if score >= 70 would be true before score >= 90 is ever tried. Put >= 90 first, then >= 80, and so on down.

Review
  • else runs when the if was false. elif tries another test only after the previous one failed.
  • Only one branch runs: the first true one. Test the strictest band first.
  • Watch each boundary: does 90 belong to A or B? Next: an if inside an if.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

elif and else — Conditional Logic · Runtime