🎓 A1Learner
🔍

Python Elif & Else

The words elif and else let one if statement test several choices in a row. Python tests the conditions from the top.

Else is the fallback

One of the two blocks always runs.

age = 15
if age >= 18:
    print("Adult ticket")
else:
    print("Child ticket")

Elif adds more tests

Python walks down the chain until one condition is true.

score = 75
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("Below C")

The first match wins

This chain is badly ordered. The loose test catches 95 before the strict test is reached.

score = 95
if score >= 50:
    print("Pass")
elif score >= 90:
    print("Excellent")

Example

score = 82
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print("Score:", score)
print("Grade:", grade)

Key points

  • Use else for the fallback block.
  • It runs when the if condition is false.
  • elif is short for else if.
  • It tests a new condition when the ones above it are false.
  • elif and else add more choices to one if statement.
  • Python tests the conditions from the top.
  • It runs the first block that matches, then stops.
  • Order matters.
  • Put the strictest tests first, or a loose test can catch a value too early.
  • The final else has no condition.
  • It catches everything that is left.

In this example, score is 82. Python tests the conditions from the top. Is 82 >= 90? No. Is 82 >= 80? Yes, so grade becomes "B". Python then skips the rest of the chain. The last two lines print the score and the grade.

Note

Python writes elif, not else if.

The shorter word keeps long chains neat.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

A grade chain tests >= 90 for A, then >= 80 for B, then >= 70 for C, then >= 60 for D, and else gives F. What grade does a score of 65 get?