Skip to contentSkip to navigation

Module 02 · Lesson 03

Conditional Branching (if / elif / else)

Let a program make decisions with if, elif and else, combine conditions, use truthy and falsy values, and keep branching code readable.

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • if, elif and else
  • Watch lines get skipped
  • Combine conditions
  • Fix an indentation error

Teach your program to decide

So far every line ran. Now some lines run only when a condition is `True`.

  • if

    if lives == 0: runs the indented lines under it only when the condition is True.

  • else

    else: catches every other case, so exactly one of the two paths runs.

  • elif

    elif adds more choices. Python checks them top to bottom and runs only the first True one.

  • Shape

    The colon ends the question. Four spaces at the start of a line put it inside the block.

Decisions everywhere

Every app makes thousands of small yes-or-no choices a second.

  • GamesIf lives reach 0, show Game Over. Else, keep playing.
  • PhonesIf the battery drops below 20 percent, show the low battery warning.
  • ThermostatsIf the room is colder than the setting, switch the heating on.
  • Video sitesIf you are old enough, show the video. Elif a parent says yes, show it. Else, hide it.

One question, one colon

The first line of every decision has the same shape. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

keyword:if starts a decision. Python is about to ask a True-or-False question.

Make decisions

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Hot or not

Two paths, and exactly one of them runs.

Your turn: Change the temperature so the other path runs. Which line runs either way?

Python
temperature = 24
if temperature > 25:
    print("Shorts weather")
else:
    print("Bring a jumper")
print("Have a nice day")
Output
Press Run to see what it prints.

Watch Python skip lines

Press Step to run one line at a time. Watch which lines Python jumps over.

Ready. Press Step to run the first line.

  1. battery = 15
  2. if battery < 10:
  3. print("Plug in now")
  4. elif battery < 20:
  5. print("Low battery")
  6. else:
  7. print("Battery fine")
  8. print("Done")

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Two separate ifs: what prints?

x = 7
if x > 5:
    print("big")
if x > 3:
    print("medium")

0 of 6 answered

Common decision misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Making decisions

So far every line of every program has run. An if statement runs a block of code only when a condition is true.

Try it 1: edit me, then Run
temperature = 31
if temperature > 30:
    print("Hot day")
    print("Drink water")
print("Have a nice day")
Output
Press Run to see what it prints.

The line starting with if ends with a colon. The lines below it that are indented by four spaces form its block. When the condition is True, the block runs; when it is False, Python skips the whole block and carries on with the first line that is not indented. Here all three messages print. With a temperature of 20, only Have a nice day would.

else: the other way

else gives a block to run when the condition is false. Exactly one of the two blocks runs, never both and never neither.

Try it 2: edit me, then Run
number = 7
if number % 2 == 0:
    print("even")
else:
    print("odd")
Output
Press Run to see what it prints.

else has no condition of its own and is lined up with its if.

elif: more than two choices

elif, short for "else if", adds more conditions. Python checks them from top to bottom and runs the block of the first condition that is true. Every later branch is skipped, even if its condition would also be true. The final else catches everything that matched nothing.

Try it 3: edit me, then Run
score = 82
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)
Output
Press Run to see what it prints.

With 82, the first test fails, the second passes, grade becomes "B", and the remaining tests are never looked at. Because Python stops at the first match, order matters. If score >= 70 came first, a score of 95 would get a C. A good rule is to put the most specific or the highest threshold first.

Use one if-elif-else chain when the options are mutually exclusive, like grades. Use separate if statements when several things can be true at once, for example printing a warning for low battery and another for no signal.

Conditions

Any expression can be a condition. The comparisons and logical operators from the operators lesson are the usual building blocks.

Try it 4: edit me, then Run
age = 15
has_permission = True
if age >= 13 and has_permission:
    print("You can join the club")
if age < 5 or age > 65:
    print("Free entry")
if not has_permission:
    print("Ask a parent first")
Output
Press Run to see what it prints.

Truthy and falsy

A condition does not have to be a bool. Python treats some values as false: False, 0, 0.0, the empty string "", None, and empty collections such as []. These are called falsy. Every other value is truthy. This makes some checks very short.

Try it 5: edit me, then Run
nickname = ""
if nickname:
    print(f"Hi {nickname}")
else:
    print("Hi there")
Output
Press Run to see what it prints.

This prints Hi there, because the empty string is falsy. Writing if nickname: reads as "if there is a nickname" and is the usual style.

Nested ifs

A block can contain another if statement. This is called nesting, and the inner block is indented one more level.

Try it 6: edit me, then Run
member = True
age = 16
if member:
    if age < 18:
        print("Junior member")
    else:
        print("Adult member")
else:
    print("Please sign up")
Output
Press Run to see what it prints.

Nesting is useful when the second question only makes sense after the first one. But deep nesting is hard to read. Two levels are fine; at three or more, look for a way to combine conditions with and, or to put the simplest case first.

A one-line choice

When you only need to pick one of two values, a conditional expression fits on one line: value_if_true if condition else value_if_false.

Try it 7: edit me, then Run
stock = 0
label = "In stock" if stock > 0 else "Sold out"
print(label)
Output
Press Run to see what it prints.

It is perfect for a short choice like this. For anything with more than two outcomes, or with several statements in each branch, a normal if statement is clearer.

Testing the edges

Most branching bugs hide at the boundaries. If a rule says "under 20", ask what happens at exactly 20, just below it and just above it. Decide whether each boundary belongs to the branch above or below, then pick < or <= on purpose. A good habit is to try a program with one value from each branch and one value sitting exactly on each boundary. For the grade chain above, that means trying 95, 90, 85, 80, 75, 70 and 10. It takes a minute and catches the mistakes that otherwise surface only when a real user hits them. The Labs for this lesson include a fix task where the order of the conditions is the bug.

Python is strict about the shape

Every if, elif and else line ends with a colon, and every block is indented consistently. A block cannot be empty; if you need a placeholder while you are still writing, use the keyword pass, which does nothing. Python 3.10 also added a match statement for choosing between many fixed values. It is covered in a later course; if-elif-else handles everything you need for now.

Syntax

The general shape of the statements in this lesson.

syntax.py
if condition:
    ...                  # runs when condition is truthy
elif other_condition:
    ...                  # first true branch wins
else:
    ...                  # nothing above matched
x = "yes" if ok else "no"   # conditional expression
# falsy: False, 0, 0.0, "", None, []
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Delivery charges

Beginner

An online shop charges 4.99 delivery under 20, 1.99 from 20 up to 50, and nothing from 50. Print the charge for three baskets.

Python
for basket in [12.5, 35.0, 50.0]:
    if basket >= 50:
        delivery = 0
    elif basket >= 20:
        delivery = 1.99
    else:
        delivery = 4.99
    print(f"Basket {basket:.2f}: delivery {delivery:.2f}")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The loop on the first line simply repeats the decision for each basket; loops are the next lesson. The chain checks the highest threshold first. For 35.0, >= 50 fails, >= 20 passes, and the else is skipped. A basket of exactly 50 gets free delivery because the test uses >=, which is the kind of boundary detail worth testing on purpose.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Missing colon

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
if score > 10
    print("High")
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

SyntaxError: expected ':'

Write this instead

if score > 10:
    print("High")

Why it happens

The colon tells Python that an indented block follows. Without it, Python cannot tell where the condition ends.

In the real world

Where this shows up in software people use every day.

  1. A smart thermostat

    Home

    A home thermostat decides every few minutes whether to heat, cool or do nothing, and it skips heating when a window is open.

    Why Python fits

    The safety check comes first so nothing else can override it. The one-degree margin on each side stops the heating from switching on and off constantly around the target.

    Python
    room = 17.5
    target = 20
    window_open = False
    if window_open:
        action = "off: window open"
    elif room < target - 1:
        action = "heat"
    elif room > target + 1:
        action = "cool"
    else:
        action = "idle"
    print(f"Room {room} C, target {target} C: {action}")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Do I always need an else?

No. If nothing should happen when the condition is false, leave it out.

Can I write if x == True:?

It works, but if x: is shorter and is the usual style. Compare to True only if you really need to tell True apart from other truthy values.

What does pass do?

Nothing at all. It fills a block that must exist but has nothing to do yet, such as a branch you plan to write later.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/5 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.