Command Palette

Search for a command to run...

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

Flat checks, pass and truthiness

Set age to 20 and run again to see the "Valid" line. Then give nickname a value and watch the last branch change.

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?

Flat checks, pass and truthiness
Sign in to run this example in your browser.

Expected output

Age cannot be negative
Age cannot be negative
Done
Empty text counts as False