Python Foundations · Lesson 4 of 12

Selection with if

Conditions, comparisons and if/elif/else. Learn through short examples, practical tasks and targeted questions.

← All lessons

Making decisions with if

Selection allows a program to take different paths depending on a condition. Python uses if, elif and else, with indentation showing which statements belong to each branch. Try values at either side of a threshold and exactly on the boundary.

Watch out: A single = assigns a value; == compares values. Confusing them causes errors in conditional expressions.

1 · Understand

Conditions, comparisons and if/elif/else. Study the code and predict what it does before running it. Change a value or string and observe how the output changes.

temperature = 18
if temperature < 10:
    print("Cold")
elif temperature < 20:
    print("Mild")
else:
    print("Warm")
Download example .py ↓

2 · Practise

Create a ticket-price decision: under 12 costs £5, 12–17 costs £7, and adults cost £10.

Plan your inputs, processing and outputs. Write the code in Mu, IDLE or PyCharm; test at least three cases.

Show a reference solution after attempting the task
age = int(input("Age: "))
if age < 12:
    print("£5")
elif age < 18:
    print("£7")
else:
    print("£10")
Download reference solution .py ↓

3 · Debug the code

Identify the problem and explain how to fix it before revealing the answer.

mark = 70
if mark >= 50
    print("Pass")
Reveal the corrected program and explanation
mark = 70
if mark >= 50:
    print("Pass")

Compare the two snippets. Identify the changed line, run the corrected version and explain the effect.

4 · Check your understanding

What is evaluated when an earlier if condition is false?

5 · Challenge and reflect

Extension: Improve your solution to deal with unexpected input, add a second feature or display results more clearly.

Reflect: What was the hardest part? What would you test if someone else used your program?

Want extra practice? Try interactive Python tracing and debugging questions →

APPLY THE IDEA

Use this skill beyond the example

Trace the condition first, deciding whether it is True or False before following either branch. Test values immediately below, equal to and above the boundary: those are the values most likely to expose mistakes.

Quick check: Which branch runs when score is exactly 50 in if score >= 50?

Check: The if branch runs because >= includes equality.