SDD  ·  Software Design & Development

Selection: if/else Statements

Lesson SDD7 of 19 Approx 60 min Requires SDD5 & SDD6 🚀 Extension Studio
Learning intentions
  • Understand what selection is and why programs need it
  • Use comparison operators to write conditions that evaluate to True or False
  • Write if, if/else, and if/elif/else statements in Python; read and trace SQA reference language
Success criteria
  • I can explain what a condition is and give examples using comparison operators
  • I can write a Python if/else statement that handles two different outcomes
  • I can write a Python if/elif/else chain that handles three or more outcomes
  • I can read and trace selection in Python and SQA reference language and predict the output for a given input
  • I can identify and correct common mistakes in selection code
Warm up — what do you already know?

Answer before the lesson begins. These check prior knowledge — it's fine if you're unsure.

1. What data type should you use to store a pupil's test score out of 100?

2. What does input() always return in Python, regardless of what the user types?

SQA uses reference language in question papers. You need to be able to read it. You will never be asked to write it.

3. A program stores a person's age as age = 16. Which Python line would correctly display their age?

Key vocabulary

selection
A programming construct that runs different code depending on whether a condition is True or False.
condition
An expression that evaluates to either True or False, e.g. score >= 50.
boolean
A data type with only two possible values: True or False.
comparison operator
A symbol used to compare two values: ==, !=, <, >, <=, >=.
if statement
Runs a block of code only when a condition is True.
else
The block that runs when the if condition is False.
elif
Short for "else if" — tests a new condition when all previous conditions were False.
indentation
The spaces at the start of a line that Python uses to mark which code belongs inside a block (4 spaces or 1 Tab).

Selection: if/else Statements

What is selection?

In everyday life, we constantly make decisions based on conditions: "If it's raining, take an umbrella — otherwise, leave it." Programming has the same idea. Selection allows a program to run different code depending on whether a condition is True or False. Without selection, a program would do exactly the same thing every single time, no matter what data was entered. Selection makes programs intelligent and responsive.

In N5 Computing Science, selection is implemented using if statements. In this lesson, you write selection in Python for code questions and read and trace the SQA reference language shown in question papers.

Comparison operators

A condition uses comparison operators to compare two values and produces a boolean result — either True or False. You must know all six operators:

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than4 < 10True
>Greater than10 > 20False
<=Less than or equal to5 <= 5True
>=Greater than or equal to3 >= 7False

The single equals sign = is the assignment operator — it stores a value. The double equals == is the comparison operator — it tests equality. Confusing them is one of the most common errors in all programming.

The simple if statement

The simplest form of selection only runs code when a condition is True. If the condition is False, nothing happens and the program moves on.

if condition:
    # code that runs only when condition is True

Two rules Python enforces strictly: the condition line must end with a colon (:), and the code inside the block must be indented (4 spaces or 1 Tab). Python uses indentation to know which lines belong inside the if — unlike many other languages that use curly braces.

The if/else statement

Often you want one thing to happen when a condition is True and something different when it is False. Add an else clause:

if condition:
    # runs when condition is True
else:
    # runs when condition is False

Exactly one of the two blocks always runs — you are guaranteed to get one outcome or the other. The else line also ends with a colon and its code is also indented.

condition True or False? YES if block runs NO else block runs program continues…
Fig 1 — Exactly one branch always runs: never both, never neither

The if/elif/else chain

When there are more than two possible outcomes, use elif (short for "else if") to test additional conditions:

if condition1:
    # runs when condition1 is True
elif condition2:
    # runs when condition1 is False AND condition2 is True
elif condition3:
    # runs when condition1 and condition2 are False AND condition3 is True
else:
    # runs when all conditions above are False

Python works through each condition in order from top to bottom. The moment one condition is True, that block runs and all remaining conditions are skipped entirely. You can have as many elif branches as you need. The else at the end is optional, but it is good practice to include it as a safety net for unexpected values.

if condition1 True? YES if block runs stops checking ✓ NO elif condition2 True? YES elif block runs stops checking ✓ NO else block always runs ✓ program continues…
Fig 2 — Python checks top to bottom and stops the moment a condition is True

Reading SQA reference language alongside Python

These examples implement the same selection logic. Read the SQA reference language on the left; write Python like the code on the right. For question-paper code answers, you may use any programming language; marks reward understanding rather than correct syntax (course specification, printed page 13).

SQA reference language (read only)Python (you write this)
IF score >= 50 THEN
  SEND "Pass" TO DISPLAY
ELSE
  SEND "Fail" TO DISPLAY
END IF
if score >= 50:
    print("Pass")
else:
    print("Fail")

Key differences: SQA reference language uses IF … THEN, ELSE, END IF and SEND … TO DISPLAY for output. Python uses lowercase if, else, colons, and indentation — there is no END IF. Python is also case-sensitive: If or IF will cause an error.

Simple IF condition True? YES run action NO continue… IF / ELSE condition True? YES if-action NO else-action continue… IF / ELIF / ELSE cond 1 True? YES action 1 NO cond 2? YES action 2 NO else continue…

Tracing selection code

An exam "trace" question gives you a piece of code and an input, then asks what the output will be. For selection, the technique is:

  1. Substitute the input value into any variables.
  2. Evaluate the first condition — is it True or False?
  3. If True, follow that branch and ignore the rest. If False, move to the next condition.
  4. Continue until one branch runs or you reach else.

Work through every condition in sequence — never assume a branch runs without checking.

Worked examples

Example 1 — Simple if statement: access check

Write a program that asks for a user's age and prints "Welcome!" only if they are 18 or older.

1
We need to get the age from the user. input() returns a string, so we convert it immediately with int().
age = int(input("Enter your age: "))
2
Write the condition: the user must be 18 or older, so we use >=.
3
Complete the if statement. Note the colon and the indented print:
age = int(input("Enter your age: "))
if age >= 18:
    print("Welcome!")
If age is 20, the condition 20 >= 18 is True → "Welcome!" is printed. If age is 15, the condition is False → nothing is printed.
Example 2 — if/else statement: pass or fail

A test is out of 100. A score of 50 or above is a pass; anything below is a fail. Write a program to display the result.

1
Get the score as an integer:
score = int(input("Enter your score: "))
2
Use if/else — there are exactly two outcomes (pass or fail), so else handles everything below 50 automatically.
3
score = int(input("Enter your score: "))
if score >= 50:
    print("Pass — well done!")
else:
    print("Fail — please try again.")
Trace with score = 72: condition 72 >= 50 is True → "Pass — well done!" is printed, else branch is skipped.
Trace with score = 34: condition 34 >= 50 is False → else branch runs → "Fail — please try again."
Example 3 — if/elif/else chain: grade bands

A marking scheme awards grades: 70+ is an A, 60–69 is a B, 50–59 is a C, below 50 is a Fail. Write the program.

1
There are four outcomes, so we need three conditions plus an else. We list them from highest to lowest — if we put the lowest condition first, nearly every score would match it.
2
Because Python stops at the first True condition, elif score >= 60 is only reached when score >= 70 was already False — so we don't need to write 60 <= score < 70; the ordering handles it automatically.
3
score = int(input("Enter your score (0–100): "))
if score >= 70:
    grade = "A"
elif score >= 60:
    grade = "B"
elif score >= 50:
    grade = "C"
else:
    grade = "Fail"
print("Your grade is: " + grade)
Trace with score = 65: first condition 65 >= 70 is False → second condition 65 >= 60 is True → grade = "B" → output: Your grade is: B.
Example 4 — String comparison: password check

Write a program that asks for a password. If it matches "open123", print "Access granted." Otherwise, print "Wrong password."

1
Passwords are text, so we use input() with no conversion — it already returns a string.
2
The comparison operator == works on strings too. Python compares them character by character, and the comparison is case-sensitive: "Open123" ≠ "open123".
3
password = input("Enter password: ")
if password == "open123":
    print("Access granted.")
else:
    print("Wrong password.")
Now you try

A leisure centre charges different entry prices depending on age: under 5 years old enter free; ages 5 to 15 pay £4; ages 16 to 64 pay £9; ages 65 and over pay £5.

Answer the following:

  1. How many outcomes does this problem have? Which type of selection should you use?
  2. Write the conditions in the correct order — explain why the order matters.
  3. Write the complete Python program that asks for the user's age and prints the correct entry price.
  1. There are four outcomes (free, £4, £9, £5), so we use an if/elif/elif/else chain.
  2. We must order conditions from the most specific/smallest value upwards (or downwards consistently). Here, checking age < 5 first makes sense; then age <= 15 (because we already know it's ≥ 5); then age <= 64; and else catches 65+. If we put a broad condition like age <= 64 first, it would catch almost everyone and nothing else would ever run.
  3. age = int(input("Enter your age: "))
    if age < 5:
        print("Entry price: Free")
    elif age <= 15:
        print("Entry price: £4")
    elif age <= 64:
        print("Entry price: £9")
    else:
        print("Entry price: £5")
Common mistakes
✕
Using = instead of == in a condition. Writing if score = 50: causes a syntax error in Python. = assigns a value; == tests equality. Use == when testing equality.
✕
Forgetting the colon at the end of if/elif/else. if score >= 50 (no colon) is a syntax error. Every if, elif, and else line must end with :.
✕
Incorrect indentation. Python uses indentation to define blocks. If the code inside the if isn't indented consistently, you'll get an IndentationError. Always use 4 spaces (or 1 Tab) and be consistent.
✕
Putting conditions in the wrong order in an elif chain. If a broad condition is checked first, narrower conditions below it may never be reached. Always think about which check should come first — typically the most restrictive.
✕
Placing elif or else after the chain has already ended. Once you write else, no further elif can follow it — else must always be last. If you write else before elif, Python raises a syntax error.
Exam tip

Read the command word carefully: a code-writing question asks you to implement logic, while a trace question asks you to predict what given code does. For trace questions, you are given code and an input and must write down the output — work through each condition in order and stop as soon as one is True. For code-writing questions, use Python. To make your Python run correctly and your logic clear:

  • Use the correct comparison operator (== tests equality; = assigns a value)
  • Include the colon after every if, elif, and else
  • Indent the code inside each block
  • Order your conditions correctly in an elif chain

Question papers show SQA reference language for you to read and trace. You do not write it. Code answers may use any programming language; marks reward understanding rather than correct syntax (course specification, printed page 13).

Task Set

Questions 1–5 are auto-checked. Questions 6–8 (including the read/trace task 7b) are self-marked — write your answer, then reveal the model answer to check your work. Questions 9–10 are practical PyCharm implementation tasks.

1. What does an if statement do when its condition evaluates to False? TYPE 1

2. Which of the following correctly checks whether a variable score is greater than or equal to 50? TYPE 1

3. What is the output of this code when the user enters 17? TYPE 1

age = int(input("Enter age: "))
if age >= 18:
    print("You can vote.")
else:
    print("Too young to vote.")

4. Which symbol must appear at the end of every if, elif, and else line in Python? TYPE 1

5. A program needs to test three different conditions in order. After checking if and finding it False, which keyword should be used for the second test? TYPE 1

6. Explain the difference between the = operator and the == operator in Python. Give one example of each in context. TYPE 2

= is the assignment operator — it stores a value in a variable. Example: score = 75 stores the integer 75 in the variable score.

== is the comparison operator — it tests whether two values are equal and returns True or False. Example: if score == 75: checks whether the value stored in score is equal to 75.

Writing if score = 75: causes a SyntaxError because you cannot use the assignment operator inside a condition.

7. Write Python code for an if/else statement that checks a variable called balance. If balance is greater than or equal to 0, print "Sufficient funds". Otherwise print "Account overdrawn". Assume balance already holds a number. TYPE 2

if balance >= 0:
    print("Sufficient funds")
else:
    print("Account overdrawn")

7b. SQA reference language (read only): trace this code. What is displayed when balance = -5, and when balance = 0? Explain which branch runs in each case. TYPE 2

IF balance >= 0 THEN
  SEND "Sufficient funds" TO DISPLAY
ELSE
  SEND "Account overdrawn" TO DISPLAY
END IF
balance = -5: -5 is not greater than or equal to 0, so the condition is False. The ELSE branch displays Account overdrawn.

balance = 0: 0 is equal to 0, so the condition is True. The IF branch displays Sufficient funds.

8. The following code contains an error. Identify the mistake, explain why it is wrong, and write the corrected version. TYPE 2

score = int(input("Enter score: "))
if score >= 70:
    grade = "A"
else:
    grade = "B"
elif score >= 50:
    grade = "C"
The mistake: elif appears after else. Once an else is written, no further conditions can be tested — else must always be the final branch. Python raises a SyntaxError because elif is not allowed after else.

Corrected version:
score = int(input("Enter score: "))
if score >= 70:
    grade = "A"
elif score >= 50:
    grade = "B"
else:
    grade = "C"

9. Practical: In PyCharm, create a new Python file called sdd7_selection.py and write a program that asks the user to enter a whole number. If the number is positive, print "Positive". If the number is zero, print "Zero". If the number is negative, print "Negative". Run your program and test it with the values 7, 0, and −3. Record the output for each test below. TYPE 3

number = int(input("Enter a number: "))
if number > 0:
    print("Positive")
elif number == 0:
    print("Zero")
else:
    print("Negative")
Expected outputs:
Input 7 → Positive
Input 0 → Zero
Input −3 → Negative

10. Practical: In sdd7_selection.py, write a second Python program that implements cinema ticket pricing: under 12 → £5; ages 12–17 → £7; ages 18–64 → £10; ages 65 and over → £6. Run the program and test it with at least four ages — one per price band. Record the output for each test below. TYPE 3

age = int(input("Enter your age: "))
if age < 12:
    print("Ticket price: £5")
elif age <= 17:
    print("Ticket price: £7")
elif age <= 64:
    print("Ticket price: £10")
else:
    print("Ticket price: £6")
Test cases:
Input 8 → Ticket price: £5 (under 12)
Input 15 → Ticket price: £7 (12–17)
Input 30 → Ticket price: £10 (18–64)
Input 70 → Ticket price: £6 (65+)

Note: Conditions are ordered from lowest to highest age boundary. Because Python stops at the first True condition, elif age <= 17 is only reached when age < 12 was already False — meaning we know age is 12 or above.
Teacher notes — Shift+T to hide

Suggested timing: 60 minutes. Warm up 5 min; vocabulary + notes 20 min; worked examples (live code) 10 min; now you try 5 min; task set 20 min.

Key misconception to address: Many pupils write if score = 50: using the assignment operator. Emphasise that == tests equality; other comparisons use the appropriate operator. A useful rule: "one equals stores, two equals compares."

Live demo suggestion: In PyCharm, deliberately write if score = 50: and show the red squiggly / SyntaxError. Then fix it to ==. Also demo an elif chain where conditions are in the wrong order (e.g. least restrictive first) and show how a score of 85 incorrectly triggers the lowest grade.

Common pupil confusion: When to use elif vs a second separate if. Explain that chained elif guarantees only one branch runs; independent if statements could each run separately. For mutually exclusive outcomes (grade bands, age groups), always use elif.

Extension question: Ask all pupils to add input validation to the cinema ticket program (Q10) — what should happen if the user enters a negative age? (Leads naturally into SDD8 complex conditions or SDD10 conditional loops.)

Notation: This is an implementation lesson: all code-writing tasks use Python, including Q7. SQA reference language is read only; use the comparison table and Q7b to practise tracing. In warm-up Q3, distinguish Python print(), design pseudocode Display, and reference language SEND … TO DISPLAY. Question-paper code answers may use any programming language and marks reward understanding rather than syntax (course specification, printed page 13).

SQA command words covered: identify, explain, write, implement, trace.