elif

Control Flow

elif

In this tutorial, we'll check several possible branches in order.

Use elif when you have more than two possible paths.

elif means "else if".

score = 72

if score >= 90:
    print("A")
elif score >= 70:
    print("B")
else:
    print("Keep practising")

Python checks the conditions from top to bottom and runs the first matching block.

Order Matters

Put the most specific or highest condition first:

score = 95

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

This prints "Pass", not "Excellent", because score >= 50 matches first.

Better:

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

Example: Temperature

temperature = 12

if temperature >= 25:
    print("Hot")
elif temperature >= 15:
    print("Mild")
elif temperature >= 5:
    print("Cold")
else:
    print("Freezing")

Only one message prints.

elif vs Several if Statements

Several separate if statements can all run:

score = 95

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

An if / elif / else chain chooses one path. Use it when the choices are alternatives.

Final else Is Optional

You do not always need an else, but it is useful when you want a fallback:

day = "Saturday"

if day == "Monday":
    print("Start of the week")
elif day == "Friday":
    print("Almost weekend")
else:
    print("Another day")

The else catches anything that did not match the earlier conditions.

Practice

Create grade messages for scores of 90+, 70+, 50+, and below 50.