elif: More Than Two Paths

Real decisions have more than two outcomes. A chain of conditions is checked in order, and the first true one wins, everything after it is skipped entirely.

Python writes elif. JavaScript writes else if. Same behavior.

Multi-way branching

PYTHON

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

JAVASCRIPT

let grade;
if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else {
  grade = "C";
}
Compare → Python contracts 'else if' into the single keyword elif. JavaScript spells it out as two words. Order matters enormously in both: the first true condition wins and the rest never run.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Change score to 95, then to 65, running it each time. Then add a branch that prints "Perfect" for a score of exactly 100.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ Order is a correctness issue, not a style choice

Flip that chain to check score >= 70 first and EVERY score above 70 prints C, because the first true condition wins and nothing after it is evaluated. In a chain of overlapping ranges, always test the most specific or highest condition first.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Nesting, Combining, and Loops Together →
← Back