13. Accumulator

An accumulator is a variable that collects a result across the passes of a loop. You set it to a starting value before the loop, update it inside the loop and use it after the loop:

  • Start with 0 when adding, 1 when multiplying, or "" when building text.
  • total += n is augmented assignment: it is the same as total = total + n.
  • The accumulator must be initialized before the loop; otherwise the first update fails with NameError.
#01

Sum a list

Use numbers = [1, 2, 3, 4]. Start total at 0, add each number with total += n inside a for loop, then print total.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Multiply a list

Use numbers = [2, 3, 4]. Start product at 1, multiply it by each number with product *= n inside a for loop, then print product.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Count matching words

Use words = ["sun", "python", "code", "hi"]. Start count at 0 and add 1 for each word with more than 3 characters. Print the final count.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Build a string

Loop over "abc". Start result at "" and add each character in uppercase with result += char.upper(). Print result.

Print exactly:

Create a free account to save your progress and unlock chapter 2.