# 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

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

``````total = 0.0
for loop over range(number of grades):

# 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:
# 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:

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

total = 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 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 + "*"
print(output)``````

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