Python Master Course V2 — 028. Loop Patterns and Accumulators
SMARTYFY ACADEMY · MODULE 03 · LESSON 028 OF 200
Loop Patterns and Accumulators
Estimated study: 60–90 minutes · Prerequisite: Lesson 027 and preceding Python foundations.
Apply counting summing filtering and min-max loop patterns.
Video lesson
Video not available yet. This position is reserved for a verified lesson video link or player. The written lesson can be completed without it.
Learning outcomes
- Use separate accumulators for counts, totals, filtered values, and extrema.
- Trace program state and predict the output.
- Recognize common errors and boundary conditions.
- Apply the concept to a complete practical project.
- Write independent tests and justify results.
Understand the technique
Accumulators summarize what has been seen
An accumulator is updated as a loop processes values. Zero starts a total or count, an empty list starts a filtered collection, and an extremum needs an actual data value or an explicit absence marker. Initialize before the loop so results survive between iterations.
State the meaning of each variable after any number of items. A total is their sum; a count is how many satisfy a condition; a filtered list contains accepted items in their original order. This invariant should remain true after every iteration.
Combine counting, summing, and filtering
These inputs are integer scores; scores of at least 60 pass. Count passes, sum their scores, and retain their values.
scores = [50, 70, 90, 40]
pass_count = 0
pass_total = 0
passing = []
for score in scores:
if score >= 60:
pass_count += 1
pass_total += score
passing.append(score)
print(pass_count)
print(pass_total)
print(passing)
Expected output:
2
160
[70, 90]
Fifty and forty change nothing. Seventy changes the accumulators to 1, 70, and [70]; ninety changes them to 2, 160, and [70, 90]. Counting adds one, summing adds the value, and append retains the value.
Initialize extrema from real data
Starting maximum at zero fails for all-negative input; starting minimum at zero fails for all-positive input. Use the first element of a nonempty list for both extrema. The project accepts a reusable list of integers; it does not accept an arbitrary one-use generator. It returns (total, minimum, maximum), or None for an empty list because no extrema exist.
Initialize total to zero when traversing the entire list. Starting total at the first element and also visiting it would double-count it. Comparing an extremum with itself is harmless.
Keep averages and memory use honest
A mean needs a total and matching count. Divide only when the count is nonzero. The passing-score mean here is 160 / 2 = 80.0. Dividing the passing total by all students answers a different question. With no passes, report an absence value such as None.
Totals and counts use a fixed number of accumulators. A retained collection can grow with the input, so keep it only when later work needs individual values. Built-ins such as sum, min, and max are useful for straightforward calculations; custom loops make acceptance rules and boundaries explicit.
Runnable example and expected output
Setup: Python 3.10 or newer, standard library only. Save the following as lesson_028.py and run python lesson_028.py (or python3).
numbers=[4,7,2]
total=0
for n in numbers:
total+=n
print(total)
Expected output:
13
Walkthrough: Identify the initial variable values, follow the control flow in execution order, and write down every printed result. Change one input, predict the new output and then run the modified program.
Guided real-world project
This function accepts a reusable list of integers. It returns (total, minimum, maximum), or None for empty input. It assumes its dataset follows that contract; it is not a general input validator.
def stats(values):
if not values:
return None
total=0
minimum=values[0]
maximum=values[0]
for value in values:
total+=value
if value<minimum:
minimum=value
if value>maximum:
maximum=value
return (total,minimum,maximum)
print(stats([8,3,12,5]))
Expected output:
(28, 3, 12)
Testing plan: Run the shown sample, add an empty or minimum-size input where applicable, and test a value at the relevant boundary. For larger systems, separate the core calculation from user input so it can be tested independently.
Common mistakes and professional practices
- Confusing an expression’s value with a side effect.
- Skipping validation of inputs and collection sizes.
- Misreading the order of operations or changes to state.
- Forgetting to test zero, empty, minimum and maximum cases.
- Using overly complicated logic instead of descriptive intermediate variables.
Debugging approach: Print the relevant state, compare each step with the expected result, isolate the first divergence, correct the underlying rule, and rerun all cases.
Think, trace, and solve
Attempt each question before revealing its answer.
1. Distinguish count from sum
count = 0
total = 0
for value in [3, 8, 5, 10]:
if value >= 5:
count += 1
total += value
print(count, total)
Predict the output.
Optional hint
List the qualifying values before updating the two accumulators.
Reveal answer and reasoning
Expected output:
3 23
Eight, five, and ten qualify: three items totaling 23.
2. Keep filter order and duplicates
Use an ordinary loop to keep positive values from [4, -1, 4, 0, 2]. Are duplicates removed?
Optional hint
append does not remove repeated values.
Reveal answer and reasoning
accepted = []
for value in [4, -1, 4, 0, 2]:
if value > 0:
accepted.append(value)
print(accepted)
Expected output:
[4, 4, 2]
Filtering excludes failing values; it does not deduplicate. Left-to-right append preserves order and both occurrences of 4.
3. Repair an invented maximum
maximum = 0
for value in [-9, -2, -6]:
if value > maximum:
maximum = value
print(maximum)
Why is the answer wrong? Give a correct initialization.
Optional hint
Ask whether the initial maximum occurs in the data.
Reveal answer and reasoning
It prints 0, which never appeared in the input. Define values = [-9, -2, -6] and initialize maximum = values[0], after checking for empty input. The correct maximum is -2.
4. Avoid double-counting
What happens if stats initializes total to values[0] and still visits every item of [8, 3, 12, 5]?
Optional hint
Count how often the first value is added.
Reveal answer and reasoning
It returns total 36 instead of 28 because 8 is included twice. Keep total at zero or deliberately skip the first item after initializing from it. Extrema can compare the first value again without changing their answer.
5. Define an empty filtered average
All scores are below 60. What should code check before calculating the passing-score mean? Why not divide by the total number of students?
Optional hint
The numerator and denominator must describe the same group.
Reveal answer and reasoning
Check pass_count > 0. When no passes exist, return None or report “No passing scores.” Dividing by all students changes the quantity and misleadingly reports zero for an empty group.
Mastery checkpoint
Before advancing, explain the main concept without notes, predict the example output, run the project, and create at least three independent tests. If your results differ, revisit the debugging section.
Summary: Apply counting summing filtering and min-max loop patterns. Reliable programs combine clear logic, appropriate validation and repeatable testing.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.