Sign in

Intro to Computer Science / Unit 6: Loops

6.3 Accumulators and Counters

3 practice questionsNot yet reviewed

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)
  • total starts at 0 and gets 1, 2, 3, 4 added: 0+1+2+3+4 = 10. The program prints 10.
  • Start the accumulator before the loop (0 for sums, 1 for products, "" for strings).
  • Counter example: count += 1 is shorthand for count = count + 1.

Practice

What does total = 0 followed by for i in range(3): total += 2, then print(total) display?
What value should a variable called product start at when multiplying numbers in a loop?
What does s = ""; for ch in "abc": s = ch + s; print(s) display?

Ready for more? Take the Unit 6 test.