Beginner 10 min

Decisions with if and else

Write Boolean conditions and follow which branch of a Python program runs.

Compare values

A comparison like temperature >= 30 produces either True or False. Equality uses ==. A single = assigns a value to a name. With and, both checks must succeed; with or, either is enough.

How it works

Read the first question at the top of the branch. If it is true, follow its indented block and continue after the branch. If it is false, move to the next condition or to else. Test the exact boundary before trying values that are clearly on either side.

Order the branches

Python tests if, then each elif, from top to bottom. It executes the first matching branch. With overlapping conditions, putting a broad test first can hide a more specific branch. Indentation establishes where each branch begins and ends.

Code example

def room_status(seats_left):
    if seats_left == 0:
        return "Full"
    elif seats_left <= 3:
        return "Almost full"
    else:
        return "Open"

print(room_status(3))

Check your understanding

Predict the room status for each number of seats left.

See the example and explanation
Example 1
Given 0
Answer Full
Example 2
Given 3
Answer Almost full
Example 3
Given 4
Answer Open

Zero matches the first branch. Values 1 through 3 match the second branch. Values above 3 reach the fallback.

Open practice problem
Next lessonLoops and counters