Intro to Computer Science / Unit 6: Loops
6.3 Accumulators and Counters
Notes
An accumulator is a variable that builds up a result as a loop runs. A counter counts how many times something happens.
total = 0
for i in range(1, 5):
total = total + i
print(total)
totalstarts at 0 and gets 1, 2, 3, 4 added: 0+1+2+3+4 = 10. The program prints10.- Start the accumulator before the loop (0 for sums, 1 for products, "" for strings).
- Counter example:
count += 1is shorthand forcount = count + 1.
Practice
What does
total = 0 followed by for i in range(3): total += 2, then print(total) display?The loop runs 3 times, adding 2 each time: 2 + 2 + 2 = 6.
What value should a variable called
product start at when multiplying numbers in a loop?Starting at 0 would make every product 0. Starting at 1 keeps the product correct.
What does
s = ""; for ch in "abc": s = ch + s; print(s) display?Each new character is placed in front: "a", then "ba", then "cba".
Ready for more? Take the Unit 6 test.