Conditionals

A free sample lesson from Python Fundamentals

The idea

Picture a fork in a path: if a sign says one thing, you go left; if it says something else, you go right - never both paths at once. In Python, if checks a yes/no question first, and only runs the code under it when the answer is True; the code under else only runs when the answer is False. Getting the fork's sign - the comparison - wrong is the single most common way this trips people up.

What it actually is

A conditional lets your program make a decision: run one block of code if something is True, and a different block if it's False. Without conditionals, a program can only ever do the exact same thing, every single time it runs.

How you write it

if condition:
    # runs when condition is True
elif other_condition:
    # runs when that one is True instead
else:
    # runs when nothing above was True

A worked example

temperature = 15
if temperature > 25:
    print("Hot")
elif temperature > 10:
    print("Mild")
else:
    print("Cold")

Python checks temperature > 25 first - False, since 15 isn't over 25. It then checks the elif: temperature > 10 - True, since 15 is over 10 - so it prints 'Mild' and skips the else completely, since only one branch of an if/elif/else block ever runs.

age = 15
if age < 13:
    print("kid")
elif age < 18:
    print("teen")
else:
    print("adult")

elif adds a third branch: Python checks each condition top to bottom and runs only the first one that is True. Here age is not under 13, but is under 18, so the elif branch runs and prints teen - the else branch is skipped entirely once a match is found.

Mistakes children actually make

Mistake 1: writing if score = 15: with a single = instead of if score == 15: - Python stops this one with a SyntaxError rather than silently misbehaving. Mistake 2: forgetting the colon at the end of the if/elif/else line, or forgetting to indent the code underneath it - Python uses that indentation to know what belongs to the if block, instead of curly braces like some other languages use. Mistake 3: writing several separate if statements instead of if/elif when only ONE branch should run - with separate ifs, Python checks every single one independently, so more than one block can run even when only the first match was intended; elif guarantees only the first matching branch runs.

Then they try it

In the app this lesson continues with the animated explanation, spoken aloud, and then the practice: score is 8, which should count as a win, but the comparison is wrong. Fix the condition so it prints 'Great job!'. The editor runs your child’s real code and checks the result, with their coding buddy reacting to what they wrote.

Try it free