Try the Jupyter notebook version.


The accumulator is a common pattern seen in programs. Suppose you are entering quiz grades for your students, and you want to calculate the average quiz grade for the class:

Number of grades: 8
grade 1: 90
grade 2: 93
grade 3: 87
grade 4: 74
grade 5: 91
grade 6: 100
grade 7: 76
grade 8: 77
Average grade = 86.0

One way to do that is with an accumulator using this pseudocode below:

total = 0.0
for loop over range(number of grades):
    # get grade using input
    # add it to total

# for loop is done here
# calculate and print average grade

The accumulator can also be useful in counting how many of the items in a list have a certain property. We won't do this until we understand branching, but here is the pseudocode:

count = 0
for loop over all items in a list:
    if item has a certain property:
        add 1 to count
# for loop is done here


The above pseudocode shows the basic syntax: initialize the accumulator before the loop, add to the accumulator in the loop, then do something with the accumulator after the loop. Here's the code to sum the quiz grades entered by the teacher:

num_grades = int(input("Number of grades: "))

total = 0
for n in range(num_grades):
    grade = float(input("grade %d: " % (n+1)))
    total = total + grade

average_grade = total/float(num_grades)
print("Average grade = %.1f\n" % (average_grade))

The total = total + grade line is where each new grade is added to the running total. After the for loop is done, the sum of all the grades should be stored in the variable total.


You can accumulate strings as well as numbers. The following code starts with a 1-character string, and then adds to it each time through the for loop.

name = input("Name? ")
output = "*"
for ch in name:
    output = output + ch + "*"

If the user types in jeff, the output is *j*e*f*f*.

challenge 1

Write a program to ask the user for miles run each day of a week whose output might look like this:

Enter your weekly milage below...

Day 1: 5
Day 2: 2
Day 3: 0
Day 4: 0
Day 5: 6
Day 6: 0
Day 7: 10

Total miles: 23.000000
    Average: 3.285714 miles per day

challenge 2

In this challenge you'll accumulate into a string instead of an integer. Ask the user for a string, then accumulate the string backwards, reversing the letters. The output might look like this:

Text: we LOVE computer science!!

!!ecneics retupmoc EVOL ew

CS21 Topics