- Understand what the SQA means by a "standard algorithm" and why these patterns appear in every exam
- Implement input validation using a conditional loop to reject values outside an acceptable range
- Implement a running total using a loop and an accumulator variable initialised to zero
- I can explain why input must be received once before the WHILE loop and again inside it
- I can write Python and SQA pseudocode for an input validation algorithm with a specific range
- I can explain why the running total accumulator must be initialised to 0 before the loop
- I can write Python and SQA pseudocode for a running total algorithm with a fixed number of items
- I can trace both algorithms step by step, updating a variable trace table as I go
- I can distinguish between input validation and a running total and know when each is needed
Answer before the lesson begins. These check prior knowledge from earlier lessons.
1. A WHILE loop runs as long as its condition is TRUE. What type of loop is this?
2. What is wrong with this code for collecting and adding 5 numbers?
for i in range(5):
number = int(input("Enter a number: "))
total = number
print("Total:", total)
3. A user is asked to enter a score between 1 and 10. They enter 15. What should a robust program do?
Key vocabulary
total = total + value.Algorithm 1 β Input Validation
What it does
Input validation keeps asking the user for a value until they enter one that is within an acceptable range. It makes programs robust β they won't crash or produce wrong answers because of invalid data.
The key pattern
The tricky part is that you must receive input once before the loop begins, and again at the end of the loop body. This is called a "read-before-loop" pattern. If you only get input inside the loop, the WHILE condition has nothing to evaluate on the first check.
SQA pseudocode
RECEIVE score FROM (INTEGER) KEYBOARD
WHILE score < 1 OR score > 10 DO
SEND "Invalid. Enter a score between 1 and 10." TO DISPLAY
RECEIVE score FROM (INTEGER) KEYBOARD
END WHILE
Python
score = int(input("Enter a score between 1 and 10: "))
while score < 1 or score > 10:
print("Invalid. Enter a score between 1 and 10.")
score = int(input("Try again: "))
How the condition works
The WHILE condition is the opposite of what you want to accept. If you want values between 1 and 10 inclusive, then the loop runs while the value is outside that range: score < 1 OR score > 10. As soon as the user enters a valid value, this condition becomes FALSE and the loop stops.
| User enters | score < 1? | score > 10? | Loop continues? |
|---|---|---|---|
| 15 | No | Yes | Yes β invalid, ask again |
| 0 | Yes | No | Yes β invalid, ask again |
| 7 | No | No | No β valid, loop ends |
Algorithm 2 β Running Total
What it does
A running total accumulates a sum by adding values one at a time inside a loop. It is used whenever you need to add up a collection of numbers β for example, the total of 5 scores, the total rainfall over 7 days, or the total cost of items in a shopping basket.
The key pattern
The accumulator variable (total) must be set to 0 before the loop begins. Inside the loop, you add each new value to the running total: SET total TO total + value. After the loop, total holds the sum of all values.
SQA pseudocode (fixed number of items)
SET total TO 0
FOR counter FROM 1 TO 5 DO
RECEIVE value FROM (INTEGER) KEYBOARD
SET total TO total + value
END FOR
SEND "Total: " & total TO DISPLAY
Python
total = 0
for counter in range(1, 6):
value = int(input("Enter a value: "))
total = total + value
print("Total:", total)
Trace table β values entered: 4, 7, 2, 9, 3
| counter | value | total (after update) |
|---|---|---|
| Before loop | β | 0 |
| 1 | 4 | 0 + 4 = 4 |
| 2 | 7 | 4 + 7 = 11 |
| 3 | 2 | 11 + 2 = 13 |
| 4 | 9 | 13 + 9 = 22 |
| 5 | 3 | 22 + 3 = 25 |
| After loop | β | 25 β |
Running total vs average
A running total gives you the sum. To calculate the average (mean), divide the total by the number of items after the loop:
average = total / 5
print("Average:", average)
Never divide inside the loop β you only have the final total once the loop has finished.
Worked examples
A program asks for a user's age to verify they are old enough to register. Age must be between 13 and 120 inclusive.
age = int(input("Enter your age: "))
while age < 13 or age > 120:
print("Invalid age. Please enter a value between 13 and 120.")
age = int(input("Enter your age: "))
print("Age accepted:", age)
Age accepted: 17.A program collects rainfall readings (in mm) for 7 days and calculates the weekly total and daily average.
total = 0
for day in range(1, 8):
rainfall = float(input("Enter rainfall for day " + str(day) + " (mm): "))
total = total + rainfall
average = total / 7
print("Weekly total:", total, "mm")
print("Daily average:", round(average, 1), "mm")
total initialised to 0 before loop begins.A program asks for 5 quiz scores, validates each one (must be 0β20), then displays the running total and average.
total = 0
for question in range(1, 6):
score = int(input("Enter score for Q" + str(question) + " (0-20): "))
while score < 0 or score > 20:
print("Invalid. Score must be between 0 and 20.")
score = int(input("Enter score for Q" + str(question) + " (0-20): "))
total = total + score
average = total / 5
print("Total:", total, "/ 100")
print("Average:", average, "/ 20")
This combines input validation (WHILE inside the FOR) with a running total. The validation runs for each question before the valid score is added to the total.
Before moving on, write SQA pseudocode for a program that:
- Asks the user to enter a temperature in degrees Celsius
- Validates that it is between -50 and 60 inclusive (keep asking if invalid)
- Does this for 3 separate days
- Calculates and displays the total temperature across all 3 days
SET total TO 0
FOR day FROM 1 TO 3 DO
RECEIVE temp FROM (REAL) KEYBOARD
WHILE temp < -50 OR temp > 60 DO
SEND "Invalid. Enter a temperature between -50 and 60." TO DISPLAY
RECEIVE temp FROM (REAL) KEYBOARD
END WHILE
SET total TO total + temp
END FOR
SEND "Total temperature: " & total TO DISPLAY
Key points: total set to 0 before the FOR loop; input validation nested inside the FOR loop; total updated after validation so only valid values are added.
while score < 1 or score > 10: without receiving a value first, Python will raise a NameError because score doesn't exist yet. Always receive the first input before the loop.
input() call inside the loop body, the value of score never changes β and an invalid score will cause an infinite loop.
score < 1 AND score > 10 can never be True for any single value β nothing can simultaneously be less than 1 and greater than 10. The condition must use OR.
total = total + value inside a loop when total hasn't been set yet causes a NameError. Always write total = 0 before the loop.
total = value instead of total = total + value. This replaces the total each iteration instead of accumulating it. After the loop, total only holds the last value entered.
The SQA names both these algorithms explicitly β they will appear in past papers by name. When a question says "implement an input validation algorithm", they expect to see: input before the loop, a WHILE with the opposite condition, an error message inside the loop, and the input repeated inside the loop.
When a question says "running total", they expect: accumulator initialised to 0 before the loop, and total = total + value inside the loop β not just a single sum at the end.
Trace table questions: If asked to trace input validation, show the variable changing each time through the loop. For running total, show the accumulator growing with each iteration β examiners are looking for evidence you understand when the variable updates.
1. What type of loop is used for input validation, and why? TYPE 1
2. An input validation algorithm is checking that a percentage entered by the user is between 0 and 100 inclusive. Which WHILE condition is correct? TYPE 1
3. Why must the running total accumulator be set to 0 before the loop, not inside it? TYPE 1
4. A running total program collects 4 values: 12, 5, 8, 15. What is the value of total after the loop? TYPE 1
5. The following pseudocode contains two errors. Identify both errors and explain the effect each would have on the program's behaviour. TYPE 2
WHILE rating < 1 OR rating > 5 DO
SEND "Invalid. Enter a rating from 1 to 5." TO DISPLAY
RECEIVE rating FROM (INTEGER) KEYBOARD
END WHILE
Error 1: There is no RECEIVE statement before the WHILE loop. The variable rating has never been assigned a value, so the WHILE condition cannot be evaluated. This would cause a runtime error (NameError in Python) as soon as the program tries to test rating < 1.
Correction: Add RECEIVE rating FROM (INTEGER) KEYBOARD before the WHILE line.
Error 2: The RECEIVE statement is at the end of the loop body, which means the error message is displayed before getting new input. While this is actually the correct structure for input validation, if the prompt before the WHILE is also missing the initial input prompt, the user would see no prompt before the first input. The algorithm is otherwise structurally correct once Error 1 is fixed β this note acknowledges that the ordering within the loop (send error β receive) is acceptable.
Note: some mark schemes also accept identifying that there is no prompt before the RECEIVE inside the loop β i.e., no message telling the user what to enter.
6. Write SQA pseudocode for a running total algorithm that collects the prices of 6 items from the keyboard and displays the total cost and the average cost per item. TYPE 2
SET total TO 0
FOR item FROM 1 TO 6 DO
SEND "Enter price of item " & item TO DISPLAY
RECEIVE price FROM (REAL) KEYBOARD
SET total TO total + price
END FOR
SET average TO total / 6
SEND "Total cost: Β£" & total TO DISPLAY
SEND "Average cost: Β£" & average TO DISPLAY
Key points: SET total TO 0 must come before the FOR loop; SET total TO total + price accumulates the sum; average is calculated after the loop using the final total.
7. Trace through the input validation algorithm below if the user enters the values 25, -3, then 7 in that order. Show the state of the number variable and whether the loop condition is True or False at each stage.
RECEIVE number FROM (INTEGER) KEYBOARD
WHILE number < 1 OR number > 20 DO
SEND "Invalid. Enter a number between 1 and 20." TO DISPLAY
RECEIVE number FROM (INTEGER) KEYBOARD
END WHILE
SEND "Accepted: " & number TO DISPLAY
TYPE 2
Before loop: RECEIVE β number = 25
Check condition: 25 < 1? No. 25 > 20? Yes β TRUE. Enter loop body.
Loop iteration 1: Send error message. RECEIVE β number = -3
Check condition: -3 < 1? Yes β TRUE. Enter loop body.
Loop iteration 2: Send error message. RECEIVE β number = 7
Check condition: 7 < 1? No. 7 > 20? No β FALSE. Exit loop.
Output: Accepted: 7
8. A teacher needs a program that collects test scores for 8 pupils (each score must be between 0 and 50 inclusive), calculates the class total, and displays whether the class average is a pass (25 or above) or a fail. Write SQA pseudocode for the complete program, combining input validation and a running total. TYPE 2
SET total TO 0
FOR pupil FROM 1 TO 8 DO
SEND "Enter score for pupil " & pupil TO DISPLAY
RECEIVE score FROM (INTEGER) KEYBOARD
WHILE score < 0 OR score > 50 DO
SEND "Invalid. Score must be between 0 and 50." TO DISPLAY
RECEIVE score FROM (INTEGER) KEYBOARD
END WHILE
SET total TO total + score
END FOR
SET average TO total / 8
IF average >= 25 THEN
SEND "Class average: " & average & " β Pass" TO DISPLAY
ELSE
SEND "Class average: " & average & " β Fail" TO DISPLAY
END IF
This solution uses three spec areas together: running total (SET total TO total + score), input validation (WHILE inside FOR), and selection (IF average ≥ 25).
9. In PyCharm, write a complete Python program that asks a user to enter their age (must be between 0 and 120 inclusive β validate this), then asks how many siblings they have (must be between 0 and 20 inclusive β validate this too). Display both accepted values and the sum of the two numbers. Test your program with at least one invalid entry for each input to confirm the validation loop works correctly. TYPE 3
age = int(input("Enter your age: "))
while age < 0 or age > 120:
print("Invalid. Age must be between 0 and 120.")
age = int(input("Enter your age: "))
siblings = int(input("Enter number of siblings: "))
while siblings < 0 or siblings > 20:
print("Invalid. Siblings must be between 0 and 20.")
siblings = int(input("Enter number of siblings: "))
print("Age:", age)
print("Siblings:", siblings)
print("Sum:", age + siblings)
Test with: age = 150 (invalid), then 25 (valid). Siblings = -1 (invalid), then 3 (valid). Expected output: Age: 25, Siblings: 3, Sum: 28.
10. In PyCharm, write a Python program for a school fundraiser. The program should ask a user how many donors there are (validate: must be between 1 and 50), then collect the donation amount from each donor (validate each: must be between Β£1 and Β£1000). After all donations are collected, display: the total amount raised, the average donation, and whether the fundraiser reached its Β£500 target. TYPE 3
num_donors = int(input("How many donors? "))
while num_donors < 1 or num_donors > 50:
print("Invalid. Number of donors must be between 1 and 50.")
num_donors = int(input("How many donors? "))
total = 0
for donor in range(1, num_donors + 1):
amount = float(input("Enter donation from donor " + str(donor) + " (Β£1βΒ£1000): "))
while amount < 1 or amount > 1000:
print("Invalid. Donation must be between Β£1 and Β£1000.")
amount = float(input("Enter donation from donor " + str(donor) + " (Β£1βΒ£1000): "))
total = total + amount
average = total / num_donors
print("Total raised: Β£" + str(round(total, 2)))
print("Average donation: Β£" + str(round(average, 2)))
if total >= 500:
print("Target reached!")
else:
print("Target not reached. Β£" + str(round(500 - total, 2)) + " short.")
This program chains all three spec areas: input validation for num_donors, running total for donations, input validation for each donation amount, and selection for the target check.
Suggested timing: 60 minutes. Warm up 8 min; notes (both algorithms) 18 min; worked examples 10 min; now you try 5 min; task set Q1βQ8 14 min; PyCharm Q9βQ10 15 min (can be set as homework).
Key misconception to address first: The "read before loop" pattern for input validation. Draw it on the board as two boxes: "get input" β "check if valid (WHILE)" β "error + get input again". Most pupils want to only ask once. Ask: "If the user enters a value and we immediately jump into the loop, what does Python try to test?" They'll realise the variable doesn't exist yet.
AND vs OR in validation: This is the most common single-mark exam error. Ask pupils: "Can a number be less than 1 AND greater than 10 at the same time?" (No.) "So we need OR β either condition being true makes the input invalid." A Venn diagram on the board helps.
Running total β live demo: In the Python REPL, start with the buggy version: total = 0 inside the loop. Run it and show that total is always just the last value. Then move total = 0 before the loop and run again. Pupils see the difference immediately.
Q10 extension: Ask pupils to also find the largest single donation (requires the find-maximum algorithm from SDD14). This connects the two lessons and builds towards assignment-level complexity.