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 isTrue.else
else:catches every other case, so exactly one of the two paths runs.elif
elifadds more choices. Python checks them top to bottom and runs only the firstTrueone.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
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?
temperature = 24
if temperature > 25:
print("Shorts weather")
else:
print("Bring a jumper")
print("Have a nice day")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.
- battery = 15
- if battery < 10:
- print("Plug in now")
- elif battery < 20:
- print("Low battery")
- else:
- print("Battery fine")
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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, []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
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.
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}")Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
if score > 10
print("High")Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Home
A smart thermostat
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.
Pythonroom = 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}")OutputPress 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?
Can I write if x == True:?
What does pass do?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.