Proof Academy · Python · Journey 04

Loops and running totals

Trace repeated instructions, repair a running total and build a program that stops when it reads a sentinel.

Lab and core lesson: 40–50 minutes, plus guided study · Builds on Selection and validation

01 · Understand and predict

What changes on each pass?

Use a for loop when you know how many times to repeat. range(1, 4) supplies 1, 2 and 3. The starting value is included and the stop value is excluded. The indented body runs once for each value supplied.

An accumulator holds a result that builds over time. Set a running total to zero before the loop. On each pass, total = total + amount reads the old total, adds the new amount and stores the result. A counter adds one per event instead of adding the amount.

total = 0
for day in range(1, 4):
    total = total + day * 2
print(total)

Worked trace

  1. Before the loop, total is 0.
  2. Day 1 adds 2, leaving 2.
  3. Day 2 adds 4, leaving 6.
  4. Day 3 adds 6, leaving 12. The loop ends before day 4 and print runs once.

Stop when a condition changes

A while loop tests its condition before each pass. This one prints 3, 2 and 1, then stops when remaining is 0. Starting at 0 skips the body. Forgetting the update would leave the condition true indefinitely.

remaining = 3
while remaining > 0:
    print(remaining)
    remaining = remaining - 1
print("Done")
If the for loop uses range(1, 3), what total is printed?

From code to machine. A Python loop revisits the same body with updated values in memory. At machine level a branch instruction can change which instruction is fetched next. The Python runtime performs this control flow while the CPU continues its fetch–decode–execute cycle.

Guided study

Read it, trace it, test it

Choose the loop from the brief

Look for the source of repetition. “Read exactly five results” gives you a count before you start, so a for loop with range(5) is a natural choice. “Read until the user enters −1” gives you a stopping condition, so a while loop is clearer. “Visit each result in this list” usually calls for for result in results. Each construct can sometimes solve the same problem, but picking the one that matches the brief helps the reader understand the intention.

range(5) gives 0, 1, 2, 3, 4. The loop does five passes even though the last index is 4. range(1, 6) gives 1, 2, 3, 4, 5. Use it if the number itself appears in a label such as Day 1. If the loop variable is never used, _ is a common name. range(2, 8, 2) gives 2, 4, 6 because the third argument changes the step. Do a quick trace whenever the start or step changes.

Trace the condition, the update and the state

count = 0
total = 0
rating = int(input())
while rating != -1:
    if 1 <= rating <= 5:
        count = count + 1
        total = total + rating
    rating = int(input())
print(count, total)
Value readrating != -1In range?count after processingtotal after processing
5TrueYes15
8TrueNo15
2TrueYes27
−1FalseBody skipped27

The first input() establishes an initial value before the condition is checked. The second is inside the loop but outside the if, so even a rejected rating leads to the next read. The sentinel controls when the loop ends and is never counted or added. The final print is outside the loop because the brief needs one result after all the data. If the first value is −1, the body never runs and both totals stay zero. This matters because you cannot assume that a condition-controlled loop will run at least once.

Diagnose three common faults

  • A total that equals only the last valid amount usually means the accumulator was reset inside the loop or assigned the latest value instead of being updated. Check its initialisation and update separately.
  • Output repeated after every amount usually means print is inside the loop. If the brief wants a final total, move it out. Keep debug prints temporarily if they help you trace, then remove them before checking exact output.
  • A loop that stalls on an invalid value usually lacks an update on that path. Try one invalid value followed by the sentinel. If it keeps running, stop the sandbox and mark every route through the body that reaches the update. If the sandbox reports EOFError instead, count the lines supplied and compare them with the calls to input().

Practise a Paper 2 change request

A school tracks completed reading sessions. The first line is the number of days, followed by one value per day. A day counts as complete when the value is at least 20. Output the number of complete days and the total minutes across those days on separate lines. Use the sandbox to create a program for this change. Start by writing a trace for five days with 19, 20, 0, 30 and 20. Then test no days, all days complete and all days below the threshold. Pick a name for each variable that says what it measures.

Read nested repetition from the inside out

If a class has three teams and each team submits two scores, the inner loop reads two scores each time the outer loop advances. There are six reads in total. Put a team subtotal inside the outer loop but before the inner loop, so it resets once per team. Put the grand total before both loops, so it keeps the contributions from all teams. Trace two teams with different scores to check that the two totals have the right lifetime.

Check your guided practice

The five-day test prints 3 and 70. Start the count and total at zero. Read the number of days once. For each of those days, read one integer and, if it is at least 20, increase the count by one and add that integer to the total. For no days use first line 0 and no further input. The loop should be skipped and both outputs should be zero. A test with 19 and 20 distinguishes an off-by-one comparison from a correct inclusive threshold.

02 · Run and repair

Three-day step total

A counter should read exactly three daily step counts and print their total once. Try 200, 300 and 500. The starter reads only two values and resets the total on every pass. Repair both logic errors.

Enter one value per line. Each input() reads the next line.

Ready to run.

Need a hint?

Place total = 0 before the loop. Use range(3) or range(1, 4) for three passes.

03 · Build independently

Collect survey ratings

Build a program that reads survey ratings until it sees −1. The number of ratings is unknown, so the stopping condition controls the loop.

  • Each input line is a whole number. Use plain input() with no prompt.
  • A rating from 1 to 5 contributes to the count and total. Ignore other integers except −1.
  • Stop as soon as −1 is read. Print the count on the first line and the sum on the second. If −1 comes first, print 0 on both lines.

Enter one value per line. Each input() reads the next line.

Ready to run.

Need a hint?

Read a rating before the while loop. While it is different from −1, process it if it is in range, then read the next rating. The update must happen for an invalid rating too.

04 · Explain and transfer

Explain your reasoning

Why does the loop read the next rating outside the range check? Give a test that would reveal the bug if the read were inside it.

Compare your explanation

The loop must advance even when a rating is rejected. With inputs 6 and −1, a read inside the range check would never run, so the condition would keep testing 6. The expected result is zero ratings and a zero total.

Independent follow-up. Write a version for donations in whole pounds. Stop at −1, ignore values below 1, and print how many accepted donations are at least £10. Trace a test that includes 9, 10, an invalid value and the sentinel.

Original GCSE practice · Pearson Edexcel 1CP2 1.2.1, 1.2.4, 1.2.5, 6.1.5–6.1.6 and 6.2.2. Download your .py file to keep it after leaving the page.

Next: Strings, lists and records →