Counting and summing patterns
In a counting task, the variable changes only when the condition is met.
Try it: Loop Tracer
How a Python for loop visits each item in turn, and how an accumulator variable (a total, a count, a best-so-far or a result list) changes on every iteration.
How it works
- Initialise the accumulator before the loop.
- Each iteration, the loop variable takes the next value from the list.
- An if inside the loop decides whether to update the accumulator.
- After the last item the loop ends and the accumulator holds the answer.
Default run (13 steps): values = [4, 9, 2, 7, 5]. Run the loop one statement at a time. … The loop has used every value. print(total) shows 27.
Simplified: A model of five fixed loop programs (sum, count, maximum, minimum, filter) run on your list — it steps the program exactly as Python would, but it does not run Python.
Loading the simulation…
Why Track Values
When a collection contains numbers, test scores, temperatures, or file contents, you may need to find something specific. You might count items that meet a condition or add selected values together. Checking every item manually is tedious and error-prone. A loop examines the items systematically while a tracking variable records what has been found so far.
A Running Count
A counting pattern uses a tracking variable to record how many items have met a condition so far. First, initialize the count. Then inspect each item during the loop. If the condition is met, update the count; otherwise, leave it unchanged. After every item has been processed, inspect the final count.
Counting Matching Items
A collection has five items. The condition is met by the second and fifth items. Trace a count that starts at zero.
- 1Initialize
Set the tracking count to zero before scanning begins.
- 2First item
The condition is not met, so the count remains zero.
- 3Second item
The condition is met, so increase the count to one.
- 4Third and fourth items
The condition is not met for either item, so the count remains one.
- 5Fifth item
The condition is met, so increase the count to two.
After the collection has been scanned, the tracking count is two.
Initialization and Updates
The tracking variable has a changing state. Its initial state comes from initialization. Its later states come from the computation performed for each item. In a counting task, the variable changes only when the condition is met. In a summing task, the variable records the running total of the values selected by the task. The loop's final state is the value to inspect after scanning is complete.
Counting Versus Summing
Counting and summing use the same overall structure, but the computation recorded by the tracking variable differs. Counting records how many qualifying items have appeared. Summing records the combined value of qualifying items. Both tasks initialize a tracker, process each item, and inspect the result after the scan.
Scanning the Same Collection in Two Ways
A collection contains the values 3, 8, and 5. Suppose the task selects the values 8 and 5.
- 1Counting interpretation
The tracker records that two items meet the selection condition.
- 2Summing interpretation
The tracker records the combined value of the selected items: 8 plus 5.
- 3Shared structure
Both tasks initialize a tracker, examine each item, update the tracker when appropriate, and inspect it after the final item.
The count is two, while the sum is 13.
Reading the Final State
What do you think happens?
A tracker starts at zero. During a scan of six items, the condition is met on the first, fourth, and sixth items. What is the tracker's final state?
Reveal answer
3
The tracker changes once for each matching item. There are three matching items, so the final count is three.
A tracking variable starts at zero and scans a collection of seven items. The condition is met by the second, third, and seventh items. Trace the tracking variable after each item and state its final value.
Hints
- Write the initial state before the first item.
- Change the tracker only when the condition is met.
- The final state is inspected after the seventh item.
A collection contains the values 4, 2, 9, and 5. The task selects 4 and 9. Describe how the tracking variable would differ for a counting task and a summing task, then give both final states.
Hints
- For counting, record the number of selected items.
- For summing, combine the selected values.
- Use the same initialization-computation-inspection structure for both tasks.
Common Tracking Errors
Common mistake Starting the tracking variable with an inappropriate value.
What it looks likeA counting task does not begin from the intended empty starting state.
Why it failsEvery later update builds on the initial state, so the final result can be offset from the correct answer.
Do this insteadChoose and verify the initialization before the loop begins.
Common mistake Updating the tracker for every item instead of only when the condition is met.
What it looks likeA count changes even for items that do not qualify.
Why it failsThe tracker no longer represents the number of matching items.
Do this insteadTie the update to the task's comparison condition.
Common mistake Using the wrong comparison operator.
What it looks likeThe loop selects a different set of items than the task requires.
Why it failsA different comparison changes which items contribute to the result.
Do this insteadCheck the comparison carefully against the intended condition.
Common mistake Inspecting the tracker before the entire collection has been scanned.
What it looks likeA partial count or partial sum is treated as the final answer.
Why it failsLater items may still change the tracking variable.
Do this insteadInspect the result after all items have been processed.
When tracing a loop, write down three things: the initial tracker value, the condition tested for each item, and the tracker value after that item. This makes the initialization-computation-inspection structure visible and helps you predict the final state.
Pattern Summary
- 1A data-scanning loop follows three parts: initialize a tracking variable, compute on each item, and inspect the result.
- 2The tracking variable changes state as the loop progresses and updates only when the task's condition is met.
- 3Counting records how many items qualify, while summing records the combined value of selected items.
- 4Initialization and comparison operators are critical because they determine the correctness of the final state.
- 5The same pattern also supports finding maximums, minimums, and other results from a collection.
At a glance
- Recognize initialization, computation, and inspection as the three parts of a data-scanning loop.
- Trace the tracking variable after each item rather than looking only at the final answer.
- Count by recording the number of matches and sum by accumulating selected values.
- Verify the starting value and comparison condition before trusting the final result.