Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.1 — Making Decisions: if, elif, else
Python · Example 1 of 2

Grades with if, elif and else

Change score to 95, 60 and 12 and predict the grade before you run. The last part shows that the first True branch wins even when later ones are also True.

if runs a block of code only when a condition is True; elif adds more conditions to try in order, and else catches everything left. Python picks at most one branch of an if/elif/else chain, and the indentation shows which lines belong to it.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Set n = 7. Print Positive if it is above 0, Negative if below 0 and Zero otherwise.

02

Set year = 2024. Print Leap year if the year is divisible by 4 but not by 100, or is divisible by 400. Otherwise print Not a leap year.

03

Set hour = 14. Print Good morning before 12, Good afternoon from 12 to 17, and Good evening from 18 on.

Explain it without notes

01

How does Python decide which branch of an if/elif/else chain to run?

02

What is the difference between a chain of elifs and several separate if statements?

03

Which values are falsy in Python, and why is if items: better than if len(items) > 0:?

04

What is a guard clause and why do programmers prefer a flat chain over deep nesting?

Grades with if, elif and else
Sign in to run this example in your browser.

Expected output

Score: 72
Grade: C
Enter the cinema
Passed (first match wins)