- Understand what a conditional loop is and when it is the appropriate loop to use
- Write WHILE loops and REPEAT…UNTIL loops using SQA pseudocode and Python
- Apply conditional loops to solve input validation problems
- I can explain the difference between a fixed loop and a conditional loop, and choose the correct one for a given problem
- I can write a WHILE loop in SQA pseudocode and Python
- I can write a REPEAT…UNTIL loop in SQA pseudocode and its Python equivalent
- I can write an input validation routine using a conditional loop
- I can trace a conditional loop step by step and state the final output
Answer before the lesson begins. These check prior knowledge from earlier lessons — it's fine if you're unsure.
1. A program needs to add up numbers entered by the user. It will stop when the user types −1. Before writing the code, can you work out how many times the loop will run?
2. Which Python operator checks whether two values are not equal?
3. What is a boolean expression?
Key vocabulary
Conditional Loops
What is a conditional loop?
A conditional loop (also called a condition-controlled loop) repeats a block of code while a condition is true — or until a condition becomes true. The defining feature is that you do not know in advance how many times the loop will run. The number of iterations is determined by what happens during the program's execution, not by a fixed number set before the loop starts.
Conditional loops are the right choice when:
- You want to keep asking the user for input until they enter a valid value (input validation)
- You want to keep processing data until a special "stop" value (sentinel) is entered
- You want to repeat an action until some condition is met
If you already know exactly how many times the loop should run — for example, always 5 scores or always 10 table entries — a fixed loop (SDD9) is the correct choice instead.
The WHILE loop
The WHILE loop checks its condition before each iteration. If the condition is false the very first time it is checked, the loop body never runs at all.
SQA pseudocode syntax:
WHILE condition DO
<loop body>
END WHILE
Python syntax:
while condition:
# loop body (indented by 4 spaces)
The condition is a boolean expression. The loop continues repeating as long as the condition evaluates to True. As soon as it evaluates to False, the loop ends and execution continues with the first line after END WHILE (or after the Python loop's indented block).
Key point: the loop body must contain code that can eventually make the condition false. If not, the loop runs forever — this is called an infinite loop.
The REPEAT…UNTIL loop
The REPEAT…UNTIL loop checks its condition after each iteration. This means the loop body always runs at least once, regardless of the condition. The loop continues until the condition becomes true — it repeats while the condition is false.
SQA pseudocode syntax:
REPEAT
<loop body>
UNTIL condition
This is different from a WHILE loop in a subtle but important way: WHILE continues while the condition is true; REPEAT…UNTIL continues until the condition becomes true (i.e., while it is false).
Python equivalent: Python has no built-in REPEAT…UNTIL construct. The closest pattern uses while True with a break:
while True:
# loop body (always runs at least once)
if condition:
break
For most N5 exam questions you will write REPEAT…UNTIL in pseudocode. In Python, you will typically use a WHILE loop with the input collected before the loop and again inside it.
Input validation — the most important pattern
Input validation is the most commonly examined use of conditional loops. The standard pattern uses a WHILE loop to keep asking the user for input until they provide a value within the acceptable range:
RECEIVE score FROM (INTEGER) KEYBOARD
WHILE score < 0 OR score > 100 DO
SEND "Invalid — enter a value between 0 and 100" TO DISPLAY
RECEIVE score FROM (INTEGER) KEYBOARD
END WHILE
In Python:
score = int(input("Enter score (0–100): "))
while score < 0 or score > 100:
print("Invalid — enter a value between 0 and 100.")
score = int(input("Enter score (0–100): "))
print("Valid score:", score)
Notice that the input is collected twice: once before the loop (so the condition can be checked immediately) and once inside the loop (so a new value is read on each iteration). If the input is only inside the loop, the condition has no value to check at the start.
Sentinel values
A sentinel value is a special value that signals the end of input — for example, entering −1 to stop adding numbers. The loop checks for the sentinel after each input and stops when it is detected:
total = 0
number = int(input("Enter a number (–1 to stop): "))
while number != -1:
total = total + number
number = int(input("Enter a number (–1 to stop): "))
print("Total:", total)
The sentinel value itself (−1) is never added to the total — the condition is checked before the addition.
Comparing fixed and conditional loops
| Feature | Fixed loop | Conditional loop |
|---|---|---|
| Number of iterations | Known before the loop starts | Unknown — depends on the condition |
| When to use | Repeat an exact number of times | Repeat until something changes |
| Pseudocode keyword | FOR … TO … DO | WHILE … DO or REPEAT … UNTIL |
| Python keyword | for | while |
| Condition checked | Not applicable | Before each iteration (WHILE) or after (REPEAT…UNTIL) |
| May never run? | No (if start ≤ end) | WHILE: yes. REPEAT…UNTIL: no |
Worked examples
Write a program that asks the user to enter a positive whole number, then counts from 1 up to that number, printing each value.
RECEIVE limit FROM (INTEGER) KEYBOARD
SET count TO 1
WHILE count <= limit DO
SEND count TO DISPLAY
SET count TO count + 1
END WHILElimit = int(input("Enter a number: "))
count = 1
while count <= limit:
print(count)
count = count + 11 2 3 4 (each on its own line). The loop ends when count becomes 5, because 5 <= 4 is false. If the user entered 0, the loop body would never run because 1 <= 0 is immediately false.A program collects an exam score from the user. The score must be between 0 and 100 inclusive. If the user enters an invalid value, the program should display an error message and ask again.
RECEIVE score FROM (INTEGER) KEYBOARD
WHILE score < 0 OR score > 100 DO
SEND "Invalid — enter a value between 0 and 100" TO DISPLAY
RECEIVE score FROM (INTEGER) KEYBOARD
END WHILE
SEND "Score accepted: " + score TO DISPLAYscore = int(input("Enter score (0–100): "))
while score < 0 or score > 100:
print("Invalid — enter a value between 0 and 100.")
score = int(input("Enter score (0–100): "))
print("Score accepted:", score)75 < 0 OR 75 > 100 is False OR False = False. The program prints Score accepted: 75.Write a program using REPEAT…UNTIL that asks the user to guess the number 42. The program keeps asking until the user is correct.
REPEAT
RECEIVE guess FROM (INTEGER) KEYBOARD
IF guess < 42 THEN
SEND "Too low — try again" TO DISPLAY
ELSE IF guess > 42 THEN
SEND "Too high — try again" TO DISPLAY
END IF
UNTIL guess = 42
SEND "Correct!" TO DISPLAYwhile True + break):while True:
guess = int(input("Guess the number: "))
if guess < 42:
print("Too low — try again.")
elif guess > 42:
print("Too high — try again.")
else:
break
print("Correct!")guess == 42, the break exits the loop and print("Correct!") runs. Note: in pseudocode, UNTIL guess = 42 means "stop when the guess equals 42" — opposite in phrasing from a WHILE condition.A program asks the user to enter positive numbers one at a time. When the user enters −1, the program stops and displays the total of all numbers entered.
SET total TO 0
RECEIVE number FROM (INTEGER) KEYBOARD
WHILE number <> -1 DO
SET total TO total + number
RECEIVE number FROM (INTEGER) KEYBOARD
END WHILE
SEND "Total: " + total TO DISPLAYtotal = 0
number = int(input("Enter a number (–1 to stop): "))
while number != -1:
total = total + number
number = int(input("Enter a number (–1 to stop): "))
print("Total:", total)−1 != −1 is false, so the loop ends. Output: Total: 35. The −1 is never added because the condition is checked before the addition.A bank ATM asks the user to enter their PIN. The PIN must be a 4-digit number — that is, a whole number between 1000 and 9999 inclusive. If the user enters a number outside this range, the ATM should display an error message and ask again. Once a valid PIN is entered, the ATM should display "PIN accepted".
Answer the following:
- Why is a conditional loop more appropriate than a fixed loop here?
- Write the pseudocode using SQA reference language.
- Write the Python code.
- A conditional loop is needed because you do not know in advance how many times the user will enter an invalid PIN. The loop must repeat until the user provides a valid value — the number of iterations depends entirely on the user's input.
-
RECEIVE pin FROM (INTEGER) KEYBOARD WHILE pin < 1000 OR pin > 9999 DO SEND "Invalid PIN — must be a 4-digit number" TO DISPLAY RECEIVE pin FROM (INTEGER) KEYBOARD END WHILE SEND "PIN accepted" TO DISPLAY -
pin = int(input("Enter your PIN: ")) while pin < 1000 or pin > 9999: print("Invalid PIN — must be a 4-digit number.") pin = int(input("Enter your PIN: ")) print("PIN accepted.")
NameError. The input must be collected before the loop so there is a value to check, and again inside the loop so a new value can be read on each pass.score < 0 OR score > 100). A REPEAT…UNTIL loop continues until the condition becomes true — so the condition describes the valid state (score >= 0 AND score <= 100). These are the logical opposites of each other.Input validation is the most commonly examined use of conditional loops. If an exam question asks you to write a loop that "keeps asking until a valid value is entered", always use a WHILE loop (not a fixed loop). The standard two-step pattern — collect input before the loop, then collect again inside it — is what markers expect to see.
When writing WHILE loop conditions for validation, remember the condition describes the invalid case. For example, if a valid age is 0–120, the loop condition is age < 0 OR age > 120. A common error is writing the valid condition instead (age >= 0 AND age <= 120), which means the loop exits immediately rather than repeating.
For trace questions involving conditional loops, draw a table with a row for each iteration and note the values after each pass. State clearly when the condition becomes false and the loop terminates. Remember — the loop body does not run on the final check, when the condition fails.
Questions 1–5 are auto-checked. Questions 6–10 are self-marked — write your answer, then reveal the model answer to check your work.
1. A program uses a WHILE loop. When does the condition get checked? TYPE 1
2. What is the key difference between a WHILE loop and a REPEAT…UNTIL loop? TYPE 1
3. What does the following code print if the user enters 3, then 7, then 5?
number = int(input("Enter number: "))
while number != 5:
print(number)
number = int(input("Enter number: "))
print("Done")
TYPE 1
4. A program uses a WHILE loop for input validation. The valid range for a temperature is −20 to 40. Which condition should the WHILE loop use? TYPE 1
5. A program collects numbers from the user until they enter 0 (the sentinel). Where in the program should the first input be collected? TYPE 1
6. Explain what would happen if a programmer wrote a WHILE loop for input validation but forgot to include a second input statement inside the loop body. TYPE 2
If the input is not collected again inside the loop body, the variable never changes. The first input stays the same on every check. If the initial value is invalid (causing the condition to be true), the condition will remain true on every subsequent check, because the value never updates. This creates an infinite loop — the program appears to freeze and never progresses to the code after the loop. The programmer must re-read the input inside the loop so that the user has the chance to enter a valid value, allowing the condition to eventually become false.
7. Write the SQA pseudocode for a program that asks the user to enter their age. The age must be between 0 and 120 inclusive. The program should keep asking until a valid age is entered, then display a confirmation message. TYPE 2
RECEIVE age FROM (INTEGER) KEYBOARD
WHILE age < 0 OR age > 120 DO
SEND "Invalid age — enter a value between 0 and 120" TO DISPLAY
RECEIVE age FROM (INTEGER) KEYBOARD
END WHILE
SEND "Age accepted: " + age TO DISPLAY
Key points: input is collected before the loop (so the condition has a value to check); the WHILE condition describes the invalid state; input is collected again inside the loop body to allow a new value each iteration; the confirmation message is after the loop, not inside it.
8. Trace through the following code. Assume the user enters: 150, −5, 72. Show the values of score at each point and state what is finally displayed.
score = int(input("Enter score (0–100): "))
while score < 0 or score > 100:
print("Invalid.")
score = int(input("Enter score (0–100): "))
print("Accepted:", score)
TYPE 2
| Step | score | Condition (score < 0 OR score > 100) | Output |
|---|---|---|---|
| Initial input | 150 | True (150 > 100) | — |
| Iteration 1 | 150 → −5 | True (−5 < 0) | Invalid. |
| Iteration 2 | −5 → 72 | False (72 is valid) | Invalid. |
| Loop ends | 72 | — | Accepted: 72 |
The loop runs twice (rejecting 150 and −5). When 72 is entered, the condition 72 < 0 OR 72 > 100 is False OR False = False, so the loop ends. Final output: Accepted: 72
9. Write a complete Python program that collects test scores from the user one at a time. The user signals they are finished by entering −1. The program should then display the total number of scores entered and the average. If no scores are entered (the user immediately types −1), display a suitable message instead. TYPE 3
total = 0
count = 0
score = float(input("Enter score (–1 to finish): "))
while score != -1:
total = total + score
count = count + 1
score = float(input("Enter score (–1 to finish): "))
if count > 0:
average = total / count
print("Scores entered:", count)
print("Average:", average)
else:
print("No scores were entered.")
The sentinel −1 is never added to total because the condition is checked before adding. The if count > 0 guard prevents a division-by-zero error if the user enters −1 immediately. float() is used so decimal scores are accepted.
10. The code below is intended to ask the user for a positive number and reject any value of 0 or below — but it contains two bugs. Identify both bugs, explain what goes wrong, and write the corrected code.
number = 0
while number > 0:
number = int(input("Enter a positive number: "))
print("You entered:", number)
TYPE 3
Bug 1 — Wrong initial value: number is initialised to 0. The WHILE condition is number > 0, which is 0 > 0 = False. The loop body never runs, so the user is never asked for input and the program immediately prints You entered: 0.
Bug 2 — Inverted condition: The loop should repeat while the number is invalid (i.e. 0 or below). The correct condition is number <= 0, not number > 0. With the current condition, the loop would exit as soon as a positive number is entered — but since bug 1 prevents the loop running at all, this cannot be seen.
Corrected code:
number = int(input("Enter a positive number: "))
while number <= 0:
print("Invalid — must be greater than 0.")
number = int(input("Enter a positive number: "))
print("You entered:", number)
The input is collected before the loop (standard pattern). The condition correctly identifies invalid values. An error message is displayed before re-reading the input.
Suggested timing: 60 minutes. Warm up 10 min; notes + comparison table 15 min; worked examples 15 min; now you try 5 min; task set 15 min.
Key misconception to address: The WHILE condition for input validation should describe the invalid case, not the valid case. Pupils frequently write while score >= 0 and score <= 100: and then wonder why the loop exits immediately. A useful framing: "the WHILE condition is a bouncer — it lets people in (continues) when the situation is bad, and stops (exits) when it is good."
Live demo suggestion: Demonstrate an infinite loop live in Python — write a WHILE loop where the input line inside the body is missing. Show the terminal hanging. Then add the missing line and re-run. The contrast makes the "must update inside the loop" rule memorable. Run in a terminal or REPL.it so pupils can see the program freeze.
Extension question: Ask pupils to combine a conditional loop with a running total: write a program that keeps collecting scores (validating each one to 0–100) until the user enters −1, then outputs the average of all valid scores entered. This chains the sentinel pattern with the validation pattern.
REPEAT…UNTIL note: Python has no native REPEAT…UNTIL construct. For exam purposes, pupils need to be able to write it in SQA pseudocode (it appears in past papers). The Python equivalent (while True: ... if condition: break) is useful to know but is less commonly examined at N5.
SQA command words covered: "write" (pseudocode and Python), "trace" (Q8), "identify" (Q10 bug-finding), "explain" (Q6, Q10).