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.
Set n = 7. Print Positive if it is above 0, Negative if below 0 and Zero otherwise.
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.
Set hour = 14. Print Good morning before 12, Good afternoon from 12 to 17, and Good evening from 18 on.
Explain it without notes
How does Python decide which branch of an if/elif/else chain to run?
What is the difference between a chain of elifs and several separate if statements?
Which values are falsy in Python, and why is if items: better than if len(items) > 0:?
What is a guard clause and why do programmers prefer a flat chain over deep nesting?
Expected output
Age cannot be negative
Age cannot be negative
Done
Empty text counts as False