Learning Goals
3 minBy the end of this lesson you can:
- Write an
ifstatement that runs only when a condition is true. - Add
elseto handle the "otherwise" path. - Chain many choices together with
elif.
Warm-Up
5 minLast lesson, input() let our programs ask the user questions. The reply always landed in a variable as a string — and int() turned numeric answers into real numbers.
Quick puzzle. If Aisyah types 15 when this short program runs, what does it print? What if she types 9?
age = int(input("Your age? ")) if age >= 13: print("Welcome to the teens.") else: print("Almost there!")
Show the answer
Typing 15 prints Welcome to the teens. because 15 >= 13 is true.
Typing 9 prints Almost there! because the condition is false — so Python jumps to the else branch.
The if statement is how Python decides. Once you have if, else and elif, your programs stop being a fixed script and start behaving like little assistants.
New Concept · Decisions in Code
12 minPart 1 · An everyday decision
Imagine you wake up in Kuala Lumpur. You glance outside.
- If the sky looks dark → bring an umbrella.
- Otherwise → leave it at home.
That's exactly the shape of an if / else in Python. The program checks something, then picks a path.
Part 2 · Comparison operators
Before if, we need a way to compare values. Python has six comparison operators. Each one returns either True or False — a Boolean.
print(5 == 5) print(5 != 3) print(7 > 10) print(7 < 10) print(8 >= 8) print(8 <= 7)
= vs ==One equals sign = assigns a value: age = 12 means "put 12 into age".
Two equals signs == compares: age == 12 means "is age equal to 12?". Mixing them up is the most common beginner bug in Python — it's the one Mei Ling found in her first quiz program!
Part 3 · The if statement
An if statement runs a block of code only when its condition is true.
temperature = 33 if temperature > 30: print("It's hot — drink water!")
Three things to notice:
- The line ends with a colon
:— Python's way of saying "a block is coming". - The next line is indented by 4 spaces. That tells Python "this line belongs inside the
if". - If the condition is false, the indented line is simply skipped.
Part 4 · else — the "otherwise" path
Add an else branch for what should happen when the condition is false.
temperature = 24 if temperature > 30: print("It's hot — drink water!") else: print("Nice weather today.")
Exactly one of the two branches runs — never both.
Part 5 · elif — many choices in a row
What if you have three or more paths? Chain them with elif (short for "else if").
score = 72 if score >= 80: print("Distinction!") elif score >= 60: print("Pass.") else: print("Try again next time.")
Python checks each line top-to-bottom. The first condition that is true wins — every later branch is skipped.
Part 6 · Indentation matters
Python uses indentation, not curly braces, to tell which lines belong together. Use 4 spaces at the start of every line that sits inside an if, elif or else.
VS Code and Thonny add 4 spaces automatically when you press Enter after a line ending in :. If your code complains about an IndentationError, check that every indented line has the same number of spaces — and that you didn't accidentally mix tabs and spaces.
Worked Example · Mamak Age Discount
12 minThe mamak shop on Jalan Bukit Bintang is running a school-holiday promo. Children pay half. Teenagers get a quarter off. Adults pay the full price. We'll build a tiny program that prints the right total. Save this as mamak_discount.py.
Code
# mamak_discount.py — work out the price after age discount # 1. Ask the customer name = input("What is your name? ") age = int(input("How old are you? ")) # 2. Full price for one nasi lemak + teh tarik full_price = 8.00 # 3. Pick a discount based on age if age < 12: discount = 0.50 # children: 50% off elif age <= 17: discount = 0.25 # teens: 25% off else: discount = 0.00 # adults: no discount # 4. Calculate the final price final_price = full_price * (1 - discount) # 5. Print the receipt print() print("Hi", name + "!") print("Full price: RM", full_price) print("Your discount:", int(discount * 100), "%") print("You pay: RM", final_price)
Two sample runs (lines you type are bold):
Output · child
What is your name? <strong>Priya</strong> How old are you? <strong>9</strong> Hi Priya! Full price: RM 8.0 Your discount: 50 % You pay: RM 4.0
Output · adult
What is your name? <strong>Wei Jie</strong> How old are you? <strong>34</strong> Hi Wei Jie! Full price: RM 8.0 Your discount: 0 % You pay: RM 8.0
What changed from PY-L1-07?
In PY-L1-07 every customer paid the same. Today our program chooses a discount based on the age the user types — same input shape, much smarter output.
Try It Yourself
13 minType each task into your editor. Run it. Try at least two different inputs before moving on.
Ask the user for a quiz score out of 100. If the score is 40 or higher, print "Pass ✅". Otherwise print "Try again 🚩".
Hint
Convert the score with int(). Use if score >= 40: for the first branch, then else: for the other.
Ask the user for a whole number. Print "Even" if it divides exactly by 2, or "Odd" if it doesn't.
Hint
Remember the remainder operator from PY-L1-04: n % 2 gives 0 when n is even. So your check is if n % 2 == 0:.
Ask for today's temperature in °C. Print one of three messages using if / elif / else:
- 32 or higher →
"Panas! Drink lots of water." - 20 to 31 →
"Pleasant — perfect mamak weather." - below 20 →
"Cool today — bring a jacket lah."
Hint
Three branches, in order from hottest to coolest. The else covers everything below 20 — no condition needed on the last line.
Mini-Challenge · Bus, LRT or Walk?
8 minBuild a tiny travel advisor that helps a friend in KL decide how to get to school.
Your file must:
- Ask for the user's
name. - Ask for the
distancein kilometres (usefloat()so half-kilometres work too). - Use
if/elif/elseto print one suggestion:
- Less than 1 km → "Just walk — it's quicker than waiting."
- 1 km up to but not including 5 km → "Take the bus."
- 5 km or more → "Take the LRT."
End by printing a friendly sign-off using the user's name.
Stretch goal. Also ask if it's raining (the user types yes or no). If the distance is short and it's raining, swap the "Just walk" suggestion for "Grab a brolly or take the bus."
Show one possible solution
# travel_advisor.py — walk, bus or LRT? # 1. Ask the user name = input("What's your name? ") distance = float(input("How far is school in km? ")) raining = input("Is it raining? (yes / no) ") # 2. Pick a suggestion based on distance if distance < 1: suggestion = "Just walk — it's quicker than waiting." elif distance < 5: suggestion = "Take the bus." else: suggestion = "Take the LRT." # 3. Stretch — adjust for rain on short walks if distance < 1 and raining == "yes": suggestion = "Grab a brolly or take the bus." # 4. Sign off print() print("Hi", name + ", here's my tip:") print(suggestion)
The line if distance < 1 and raining == "yes": sneaks ahead to PY-L1-10 (and). Don't worry if your version uses a nested if instead — both are correct.
Recap
3 minOur programs can now choose. We compared values with ==, !=, < and friends, and used if / elif / else to pick a path. Indentation tells Python which lines belong inside each branch.
Vocabulary Card
- condition
- A piece of code that is either
TrueorFalse, likeage >= 12. - if
- Runs the indented block only when its condition is true.
- elif
- "Else if" — checked only when every condition above it was false.
- else
- The catch-all branch. Runs when nothing above it matched.
Homework
4 minCreate a new file called grader.py — a simple grade calculator for a Malaysian school exam.
Rules:
- Ask the user for their
nameand theirscoreout of 100. - Convert the score with
int(). - Use
if/elif/elseto print one of these grades:
- 80 and above →
A - 65 to 79 →
B - 50 to 64 →
C - 40 to 49 →
D - below 40 →
Fail
Print one friendly multi-line reply that names the student, shows their score and their grade. Bring the file to next lesson — we'll trade scripts and try to break each other's logic!
Sample · grader.py
# grader.py — turn a score out of 100 into a letter grade # 1. Ask the student name = input("What is your name? ") score = int(input("Your score out of 100? ")) # 2. Pick a grade — order matters, highest first if score >= 80: grade = "A" elif score >= 65: grade = "B" elif score >= 50: grade = "C" elif score >= 40: grade = "D" else: grade = "Fail" # 3. Friendly reply print() print("Hi", name + "!") print("Your score:", score) print("Your grade:", grade)
Yours might use slightly different cut-offs or messages — that's fine. The key is that every score from 0 to 100 lands in exactly one branch.