EMZETT.
Login

else…if

In short: A chain of several conditions, where it’s checked in sequence which one matches first — as soon as one condition is true, all further ones in the chain are skipped.

In more detail: else...if chains are useful when more than two mutually exclusive cases have to be distinguished (e.g. grade levels based on a score). For very many fixed comparison values against the same expression, a switch statement is usually preferred, because it’s clearer than a long else...if chain.

In Depth

if score >= 90:
    grade = "Excellent"
elif score >= 75:
    grade = "Good"
elif score >= 60:
    grade = "Satisfactory"
else:
    grade = "Failed"

The decisive behaviour: the conditions are checked from top to bottom, and as soon as the FIRST matching condition is found, only its block runs — all further elif/else if branches below it are completely skipped, even if their condition would theoretically also match. This distinguishes an else...if chain from several independent if statements in a row, where EVERY condition is checked individually and potentially several blocks would run:

# DANGEROUS: several independent if statements instead of a chain
if score >= 90:
    grade = "Excellent"
if score >= 75:        # ALSO checked, even if the first already matched!
    grade = "Good"         # overwrites "Excellent" again if score >= 90

The order of the conditions is therefore crucial and has to be chosen deliberately — for overlapping ranges (as here: 95 points satisfies both >= 90 and >= 75), the most specific/strictest condition has to come first, otherwise the wrong one wrongly “wins”.

When is an else...if worthwhile over a switch statement? A switch is only suitable when all cases check for exact equality with a single value (e.g. case 1:, case 2:). An else...if chain, by contrast, is the only option when the conditions check different expressions, ranges (>=, <), or several variables at once — exactly as in the grade example above, where every condition covers a number range instead of a single value.

See also: if…else, if Statement, Switch Statement