Skip to the content

Accumulators

Python · Unit 3: Loops

To add up many numbers, create a variable at 0 before the loop.

On each round, add the number of that round to it. At the end it holds the total.

total = 0
for n in range(1, 5):
    total = total + n
print(total)

Prints

10

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Find the bug

    This program should add up the three grades the person types. Which line has the error?

  4. 4. Complete the code

    Complete this to add up the numbers from 1 to 5.

  5. 5. Predict the output

    What does this code print?

  6. 6. Predict the output

    How many rounds does this code count?

  7. 7. Predict the output

    What does this code print?

  8. 8. Put the lines in order

    The person types four grades. Put the lines in order to count how many are passing (60 or more).

  9. 9. Find the bug

    This program should print the multiples of 5 from 1 to 20 and how many there are. Which line has the error?

  10. 10. Complete the code

    Complete this to work out 1 x 2 x 3 x 4.

  11. 11. Write the code

    Write sum_up_to(n), which returns the sum of all the numbers from 1 to n. For example, sum_up_to(4) gives 10.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →