Python practice: Trace loops and test your code in the sandbox.
Learning route
Trace every update. Stop at the right moment.
Prerequisite: Can read an integer, write an if / elif / else chain, and test a boundary. Complete Lesson 01 first if needed.
- Choose a for loop for a known count and a while loop for a condition.
- Trace a counter and an accumulator without skipping the initial state.
- Use a sentinel to end input without adding it to the total.
- Reject out-of-range values and test termination as well as totals.
Retrieve and explain
- For age 17, evaluate
age >= 12 and age <= 17. - What does
total = total + 4do if total is currently 6? - Why should a variable be assigned a value before it is read?
- Give a test immediately outside the valid range 0–10.
A for loop is useful when the number of repetitions is known. A while loop checks a condition before each repetition, so it may execute zero times.
total = 0
for number in range(1, 4):
total = total + number
print(total)
| Point | number | total |
|---|---|---|
| Before loop | Not assigned yet | 0 |
| After first body | 1 | 1 |
| After second body | 2 | 3 |
| After third body | 3 | 6 |
range(1, 4) supplies 1, 2 and 3: the stop value is excluded. An accumulator combines values, such as a running total. A counter counts events, usually by adding 1.
attempts = 0
while attempts < 3:
print("Try")
attempts = attempts + 1
The loop needs a route to stopping.
For a condition-controlled loop, identify the initial state, condition and update. If nothing changes the condition, a loop that starts true may continue indefinitely. Moving an accumulator’s initialisation inside the body erases previous progress.
Worked example
A collection counter reads non-negative whole numbers. A sentinel of −1 ends the input. The sentinel is a control signal, not a contribution. Assume all other inputs are non-negative.
total = 0
amount = int(input("Amount (-1 to stop): "))
while amount != -1:
total = total + amount
amount = int(input("Amount (-1 to stop): "))
print("Total:", total)
| Input read | Condition amount != -1 | total after body |
|---|---|---|
| 4 | True | 4 |
| 6 | True | 10 |
| −1 | False | No body; total remains 10 |
The first input is read before the condition. Each later input is read at the end of the body. If the very first input is −1, the body never runs and the total is 0.
Repair practice
The program should total three integer scores. Diagnose both faults before rewriting it.
for attempt in range(1, 3):
total = 0
score = int(input("Score: "))
total = total + score
print("Total:", total)
Use scores 2, 4, 6. Record how many prompts appear and what the final output should be. Explain why changing only the range is not enough.
Repair feedback
total = 0
for attempt in range(3):
score = int(input("Score: "))
total = total + score
print("Total:", total)
range(1, 3) repeats twice; use range(3) or range(1, 4). Initialising total inside the body discards earlier scores. The original program reads 2 and 4 and prints 4. With both faults repaired it reads all three and prints 12. Just fixing the range would print 6.
Independent practice
Independent build: training-session scores. Repeatedly read a whole-number score. Scores 0–10 are valid. −1 ends the session. Other values output Invalid score and do not affect the total or count. On exit, output labelled Total: and Count:.
- Initialise total and count to zero.
- Read the first score, then repeat while it is not −1.
- Use selection inside the loop to accept or reject each score.
- Read a new score on every pass, including after an invalid value.
- Test an immediate stop, a zero, two valid scores and invalid values on both sides.
Required test sequences: −1; 0, −1; 4, 6, −1; −2, 11, 10, −1. The input conversion assumes whole-number text.
# Proof Academy | Lesson 02 | Training-session scores
# Whole-number inputs. -1 stops. Valid scores: 0 to 10.
# Other values: print Invalid score; do not count or total them.
total = 0
count = 0
# Your task: read the first score.
# Your task: loop until -1; validate, update total/count, read again.
# Your task: display labelled Total and Count.
Model program and marking guidance
# Proof Academy | Lesson 02 | Worked solution
total = 0
count = 0
score = int(input("Score (-1 to stop): "))
while score != -1:
if score >= 0 and score <= 10:
total = total + score
count = count + 1
else:
print("Invalid score")
score = int(input("Score (-1 to stop): "))
print("Total:", total)
print("Count:", count)
- Initialises total and count once before accumulation. [1]
- Reads a score and stops at −1 without processing the sentinel. [1]
- Accepts both endpoints 0 and 10, rejecting other non-sentinel values. [1]
- Adds only valid scores to total. [1]
- Increments count only for valid scores (including zero). [1]
- Reads the next score after every pass, including invalid input. [1]
- Outputs labelled final total and count after termination. [1]
- Records expected and actual outcomes for all four required test sequences. [1]
Exam practice
Original Proof Academy practice · 6 marks. Trace this program without running it.
x = 1
total = 0
while x < 4:
total = total + x
x = x + 1
print(total)
- Record x and total after each complete loop body. [3]
- State the output. [1]
- Explain what happens if
x = x + 1is removed. [2]
Worked feedback
| After body | x | total |
|---|---|---|
| 1 | 2 | 1 |
| 2 | 3 | 3 |
| 3 | 4 | 6 |
One mark per correct row (3); output 6 (1). Without the update, x stays 1 (1), so x < 4 stays true and the loop repeatedly adds 1 without reaching the final print (1). Accept a coherent trace that clearly labels values before rather than after the update, provided it shows all required states.
Homework and feedback
30 minutes: 5 minutes trace retrieval, 15 minutes coding, 10 minutes testing.
Read a whole-number temperature repeatedly until 999. Valid temperatures are −20 to 50 inclusive. Reject all other values with Invalid temperature. Count accepted readings below 0; output Below zero: followed by the count when the sentinel is entered. Test 999 and −21, −20, −1, 0, 50, 51, 999. Explain why 999 must not be counted or reported as invalid.
Homework feedback
below_zero = 0
temperature = int(input("Temperature (999 to stop): "))
while temperature != 999:
if temperature < -20 or temperature > 50:
print("Invalid temperature")
elif temperature < 0:
below_zero = below_zero + 1
temperature = int(input("Temperature (999 to stop): "))
print("Below zero:", below_zero)
Immediate 999 → Below zero: 0. The longer sequence rejects −21 and 51, and counts −20 and −1, so Below zero: 2. The loop condition handles the sentinel before validation; it is a control value, not a temperature reading.
Sources and further practice
This chapter is written for Pearson Edexcel GCSE Computer Science 1CP2. Use the specification references in the chapter heading to locate the relevant requirements. Practice questions and point allocations on this page are original Proof Academy teaching material unless a question is explicitly identified as a sourced past-paper bridge.
- Pearson Edexcel 1CP2 specification
- PMT Paper 1 papers and mark schemes
- PMT Paper 2 papers and mark schemes
When using an original paper, open its matching mark scheme and supplied coding files where required. Use that paper's instructions and marks. A short classroom exercise is not a substitute for a full official task.
Trace lab · inline, no inner scroll
Sentinel total
Amounts are added until −1. The sentinel is not included.
Keep your evidence
Export your notes before changing devices.
Notes stay in this browser. The Quiz tab records the chapter check, and Resources holds the long-answer questions.