TracksPractical Coding FoundationsControl FlowUsing If and Else(3 of 11)

Using If and Else

Now that you understand conditions, let's use them to control which code runs. The if statement is your primary tool for making decisions in Python.

The Basic If Statement

An if statement runs code only when its condition is True:

age = 20

if age >= 18:
    print("You are an adult")

Notice the structure: the keyword if, followed by a condition, followed by a colon. The code that runs when the condition is true is indented underneath. This indentation isn't optional — it's how Python knows which code belongs to the if statement.

Adding Else

What if you want to do something different when the condition is False? That's what else is for:

age = 15

if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

The else clause runs when the if condition is False. You get one path or the other, never both.

Multiple Conditions with Elif

Sometimes you need more than two paths. The elif keyword (short for "else if") lets you check additional conditions:

age = 18

if age >= 21:
    print("Can drink alcohol")
elif age >= 18:
    print("Can vote")
else:
    print("Minor")

Python checks conditions from top to bottom and runs the first block whose condition is True. Once it finds a match, it skips the rest. If nothing matches, the else block runs.

You can chain as many elif statements as you need:

score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("F")

Indentation Matters

Python uses indentation to define code blocks. Everything indented under an if, elif, or else belongs to that branch:

if logged_in:
    print("Welcome back!")
    show_dashboard()  # Also part of the if block
print("This always runs")  # Outside the if block

Consistent indentation (typically 4 spaces) keeps your code readable and prevents errors.

See More

Further Reading

You need to be signed in to leave a comment and join the discussion