Programming I · Loops and accumulators
Trace a loop one iteration at a time, select the right range boundaries, and explain why an accumulator gives the expected result.
Before you start
Review assignment, integer comparisons, the remainder operator, and if statements.
Iteration and state
An iteration is one execution of a loop body. A Python for loop visits successive items of an iterable. The indented body runs once per item and can update variables that persist into the next iteration. An accumulator starts with an initial value and combines each item with the running result. For addition the initial value is zero, which also gives the sum of an empty sequence.
For integer arguments, range(start, stop, step) includes start when it is on the correct side of stop. A positive step continues while the value is less than stop, and a negative step while it is greater. The stop value is excluded and a zero step raises ValueError. A while loop instead tests a condition before each iteration and may run forever if that condition never becomes false.
| Step | New item | Total afterward |
|---|---|---|
| 0 | — | 0 |
| 1 | 2 | 2 |
| 2 | 4 | 6 |
| 3 | 6 | 12 |
Why the trace proves the result
The invariant is that total equals the sum of all items already processed. It holds before the first iteration because an empty sum is zero. Adding the next item preserves it. When a finite iterable is exhausted, all items have been processed, so total is the complete sum.
Worked examples
total = 0
for value in range(2, 7, 2):
total += value
print(total)
The visited values are 2, 4, and 6. Each is less than 7, and the next value 8 fails the boundary test. The trace ends at 12.
count = 0
for value in [3, 0, 4, 7]:
if value % 2 == 0:
count += 1
print(count)
Only 0 and 4 satisfy the condition. After each iteration count is the number of even items visited so far. The output is 2.
Common mistakes
Initialize the accumulator before the loop so earlier work survives. Test empty, single-item, and boundary cases. In a while loop, check which update can make the condition false.
Practice
- List the values of range(1, 5).
- Give the running totals for range(5, 0, -2).
- How would you count strictly positive items of an arbitrary finite list? State the invariant and empty-list result.
Worked practice solutions
- The values are 1, 2, 3, 4. Python excludes the stop value 5.
- The visited values are 5, 3, and 1, all greater than 0. The totals are 5, 8, and 9. The next value −1 ends the range.
- Start count at zero. For each item, add one only if item > 0. After each iteration count equals the number of positive items already visited because only a positive item can increase it. With no items there are no updates, so the result is zero.
Assessment · Open book · 16 points
Open book: use books, lesson notes, cited readings, calculators, and relevant free software. Explain your own reasoning, assumptions, units, and checks; identify references or software you use. Attempt the questions before opening the answer key. Suggested study time: 40–60 minutes; this is a self-study guide, not a timed restriction.
A loop starts total at zero and adds each item of range(2, 9, 3). Give its items (3 points), running totals (3), and invariant (2). What does it return if stop is changed to 2, and why (2)?
Application and reasoning · 6 points
A proposed sum of 1 through n starts total=0 and uses “for i in range(1,n): total=i”. For integer n≥0, repair both bugs (2), give an invariant explaining correctness (2), and provide boundary and ordinary tests that detect the original faults (2).
Complete answer key and scoring rubric
- One point each for 2, 5, 8 and for totals 2, 7, 15.
- Two points for stating total is the sum of visited items. One point for an empty range when start equals stop and one point for total staying zero.
Application and reasoning · 6 points
Use range(1,n+1) and total+=i (1 each). After visiting i, total is 1+…+i=i(i+1)/2; initialization is 0 and adding the next item preserves the visited-sum invariant (2). n=0→0, n=1→1 catches the excluded end, and n=3→6 catches replacement instead of accumulation (2 for tests with purposes).
Scoring: existing questions 10 + application problem 6 = 16 points. Award the stated method and reasoning marks, not only final answers.
Loop lab · Trace a running sum
Predict which values a Python-style range yields and when the sum changes.
Free tool built into this page. Use it in your browser without an account or download.
Procedure
Predict the visited values and total. Try (start, stop, step) = (2, 7, 2), (2, 6, 2), (5, 0, −2), and (2, 2, 1). Which case excludes 6, and why does the empty case stay at zero?
Expected results and answer check
Totals are 12, 6, 9, and 0. The second run visits 2 and 4 only because 6 is its excluded stop. In the last run the first candidate already equals stop, so the body never runs.
This built-in model traces a fixed summing loop over small integer ranges. It does not execute arbitrary Python.