Module 3

Repeating calculations

Using loops to compute values.

Adding up values

A common pattern is to start with a variable at zero and add to it in each iteration. This is called accumulating.

Python
total = 0
for num in [10, 20, 30]:
    total = total + num
print(total)
60

The variable total starts at 0. Each time through the loop, the current number is added to total. After the loop, total holds the sum.

Your task

Accumulate values

  • Sum the numbers 10, 20, 30 using a loop and print the total.