The basics of syntax

INPUT · Slides

Splitting it more ways

01 / 06

When two is not enough

You want to grade work as A, B or C. if and else only get you two.

So: elif. It is a squashed-up else if, and it means "otherwise, if...".

02 / 06

The shape of an elif

Between the if and the else, write elif condition:. You can have as many as you like.

Unlike else, an elif takes a condition. The else goes last, on its own, with no condition.

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

Result

B

03 / 06

Top to bottom, and only the first one

This is the crucial bit. Python works down the conditions in order and runs only the first one that holds.

The rest are skipped entirely, whether they would have held or not. That is why exactly one road is always taken.

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

Result

A

04 / 06

Get the order wrong and it breaks

So what if you flip the conditions round? Even 95 comes out as B.

>= 70 is checked first, so anyone at 90 or above gets caught there. A will never appear at all.

Write the strictest condition first. That is the rule with elif.

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

Result

B

05 / 06

The else can be left out

You can line up elifs and write no else at all. In that case, if none of them holds, nothing happens.

Just ask yourself each time whether letting something fall through is really all right. Keeping an else means you notice values you never expected.

score = 30if score >= 90:    print("A")elif score >= 70:    print("B")

06 / 06

It is not the same as two ifs

Use separate ifs instead of elif and every condition that holds will run.

In the example below, both A and B come out. If you want "one of these", you have to join them with elif.

score = 95if score >= 90:    print("A")if score >= 70:    print("B")

Result

A
B