- Understand what the SQA means by a "standard algorithm" and why these patterns are useful
- 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 the read-before-loop validation pattern and why invalid input must be received again
- I can write Python code 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 code for a running total algorithm with a fixed number of items
- I can read and trace both algorithms in SQA reference language, 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?
for counter 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 — the examples below prevent out-of-range numbers from reaching later calculations.
The key pattern
In the read-before-loop version shown here, 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 input appears only inside the loop and the variable has not been initialised first, the WHILE condition has no value to evaluate on its first check. A correctly initialised variable or a while True loop with an exit on valid input can also implement validation.
This builds on conditional loops from SDD10, but the purpose is now more specific: the loop protects the rest of the program from an out-of-range value. The earlier lesson taught how a WHILE loop repeats; this version uses the order of operations — read, test, explain the error, then read again — so only valid data reaches later calculations.
SQA reference language (read only)
SQA uses reference language in question papers. You need to be able to read it. You will never be asked to write it.
Read the diagram and reference-language example. The first read supplies a value for the condition; each invalid value triggers an error message and another read. A valid first input needs no second read. Q7 asks you to trace this pattern.
SQA reference language (read only)
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: total = total + value. After the loop, total holds the sum of all values.
This develops the fixed-loop work from SDD9. The loop controls how many values are processed, while the accumulator preserves information between iterations. These are separate jobs: the counter tracks progress through the loop; total stores the growing sum. Resetting total inside the loop destroys that memory and leaves only the final value.
SQA reference language (read only)
Read this fixed-loop example and compare it with Python below. Reference-language FROM 1 TO 5 includes 5; Python range(1, 6) stops before 6. Both process exactly five inputs.
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)
Calculate this final average after the loop, once all values have been added. An intermediate average can be computed inside a loop when a task specifically requires one.
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 Python code 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
Hint: Use a three-iteration for loop, a while loop to reject temperatures outside the range, and float(input(...)). Add each accepted temperature to the total.
total = 0
for day in range(1, 4):
temp = float(input("Enter temperature for day " + str(day) + ": "))
while temp < -50 or temp > 60:
print("Invalid. Enter a temperature between -50 and 60.")
temp = float(input("Try again: "))
total = total + temp
print("Total temperature:", total)
Key points: total = 0 comes before the Python for loop; range(1, 4) gives three days; input validation is nested inside the loop; total is updated after validation so only valid temperatures are added. For inputs 70 then 10, -50 and 60, the error appears once and the final output is Total temperature: 20.0. Any correct Python solution is valid.
while score < 1 or score > 10: without receiving a value first, Python will raise a NameError because score doesn't exist yet. In this read-before-loop version, 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 course specification names both algorithms. For a write-code question, use Python to implement the required logic. Our read-before-loop validation pattern receives input, repeats while the value is invalid, displays an error and receives another value. Other correct implementations are valid.
For a design question, use structured-English pseudocode. The 2024 marking instructions, Q11(a)(i) credit a conditional loop, a valid 5–75 range condition, input inside the loop and an error message inside the loop; design intention matters. Any clear alternative design is accepted.
For a running-total implementation, use: 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
SQA reference language (read only)
2. Read the options. 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
SQA reference language (read only)
WHILE rating < 1 AND 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 invalid-range condition uses AND. A rating cannot be less than 1 and greater than 5 at the same time, so the condition is always False and invalid values are accepted. Replace AND with OR, because a value is invalid when it is below 1 or above 5.
6. Write Python code 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
Hint: Initialise total, repeat six times using range(1, 7), receive each price with float(input(...)), then divide the completed total by 6.
total = 0
for item in range(1, 7):
price = float(input("Enter price of item " + str(item) + ": "))
total = total + price
average = total / 6
print("Total cost: £" + str(round(total, 2)))
print("Average cost: £" + str(round(average, 2)))
Key points: total = 0 comes before the loop; range(1, 7) processes six prices; total = total + price accumulates the sum. Calculate the average after the loop. For inputs 1, 2, 3, 4, 5 and 6, the results are Total cost: £21.0 and Average cost: £3.5. Any correct Python solution is valid.
SQA reference language (read only)
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 Python code for the complete program, combining input validation and a running total. TYPE 2
Hint: Repeat for eight scores. Validate each score inside that loop before adding it to the total. Calculate the average after all eight valid scores, then use selection for pass or fail.
total = 0
for pupil in range(1, 9):
score = int(input("Enter score for pupil " + str(pupil) + ": "))
while score < 0 or score > 50:
print("Invalid. Score must be between 0 and 50.")
score = int(input("Try again: "))
total = total + score
average = total / 8
if average >= 25:
print("Class average:", average, "— Pass")
else:
print("Class average:", average, "— Fail")
This Python solution combines a running total (total = total + score), input validation (while inside for) and selection (if average >= 25). Eight inputs of 25 give Class average: 25.0 — Pass; eight inputs of 24 give Class average: 24.0 — Fail. An input of 51 must be rejected and replaced before it affects the total. Any correct Python solution is valid.
9. Practical: In PyCharm, create a new Python file called sdd15_validation_totals.py. Ask for an age from 0 to 120 and a number of siblings from 0 to 20, validating both. Display both accepted values and their sum. Test with age 150 then 25, siblings -1 then 3; then test with age 0 and siblings 20. Record both complete outputs. 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)
Expected console transcript, including entered values — Test 1:
Enter your age: 150 Invalid. Age must be between 0 and 120. Enter your age: 25 Enter number of siblings: -1 Invalid. Siblings must be between 0 and 20. Enter number of siblings: 3 Age: 25 Siblings: 3 Sum: 28
Expected console transcript — Test 2:
Enter your age: 0 Enter number of siblings: 20 Age: 0 Siblings: 20 Sum: 20
10. Practical: In sdd15_validation_totals.py, replace the previous program with a fundraiser program. Validate 1–50 donors and each donation from £1 to £1000, then display the total, average, and whether the £500 target was reached. Test with three donations of 200, 150, 175; then two donations of 100, 50. Record both complete outputs. 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.")
Expected result lines for 3 donors entering 200, 150, 175:
Total raised: £525.0 Average donation: £175.0 Target reached!
Expected result lines for 2 donors entering 100, 50:
Total raised: £150.0 Average donation: £75.0 Target not reached. £350.0 short.
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 first input statement is only inside the loop and score has not been initialised, what does the first condition check try to read?" Explain that this version has no value to test yet; correctly initialised-variable and while True alternatives are valid.
AND vs OR in validation: 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.
Notation separation: Now you try, Q6 and Q8 ask for Python implementation. Q2, Q5 and Q7 read SQA reference language; pupils explain or trace it without writing a reference-language solution. Design answers use structured English, accepting any clear alternative. The examples validate numeric ranges; non-numeric input would need additional handling.
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.