acculumators

Try the Jupyter notebook version.

motivation

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 in 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 item in list:
  if item has a certain property:
    add 1 to count
# for loop is done here
print(count)

syntax

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:

In [5]:
num_grades_s = input("Number of grades: ")
num_grades = int(num_grades)

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

average_grade = total/num_grades
print("Average grade =", average_grade)
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

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.

examples

You can accumulate numbers, as well as strings. The following code starts with an empty string, and then adds to it each time through the for loop. Note that in the for loop below, we are not really using the loop variable, i. We just use the loop to accumulate the string.

In [4]:
name = input("What is your name? ")
output = "*"
for i in range(len(name)):
  output = output + name[i] + "*"
print(output)
What is your name? Rich
*R*i*c*h*

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
In [ ]:
 

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
In [ ]: