Course outline · 0% complete

0/32 lessons0%

Course overview →

The Four Loop Patterns

lesson 5-3 · ~13 min · 15/32

Sum and count: the accumulator

Almost every loop you will ever write is one of four patterns: sum, count, find, or build. All four share one idea, the accumulator: a variable created before the loop that each pass updates.

total = 0
count = 0
for n in range(1, 101):
    if n % 3 == 0:
        total = total + n
        count = count + 1

Shorthand you will see everywhere: total += n means total = total + n (works for -=, *= too).

One more tool first: in tests membership. "e" in "hello" is True. It works on strings now and on every collection in the coming units.

Code exercise · python

Run the sum-and-count pattern over the multiples of 3 up to 100.

Find and build

Find scans for the first item that matches, then stops (that was your while n % 7 != 0 in lesson 5-2, and break does it in a for).

Build constructs a new value piece by piece. With strings, start from "" and concatenate, meaning join strings end to end with +:

result = ""
for ch in "hello world":
    if ch != "o":
        result = result + ch
print(result)   # hell wrld

Name the pattern before you write the loop. I am counting matches or I am building a cleaned-up string tells you what the accumulator is, what it starts as, and what each pass does to it.

Code exercise · python

Run the find pattern in a for loop: scan numbers upward and stop at the first multiple of 13 past 500. The break matters for more than correctness, it stops the scan the instant the answer is found instead of checking everything after it.

Code exercise · python

Your turn. Count the vowels (a, e, i, o, u) in the sentence. Use the count pattern with `ch in "aeiou"` as the test.

Problem

Trace this loop by hand. What single number does it print? ```python total = 0 for i in range(4): total += i print(total) ```