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:
$ python average.py
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:
total = 0.0
for loop over range(number of grades):
get grade
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 pseudo code:
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
print out count
The above pseudo code 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:
ngrades = int(raw_input("\nNumber of grades: "))
total = 0
for n in range(ngrades):
grade = float(raw_input("grade %d: " % (n+1)))
total = total + grade
avegr = total/float(ngrades)
print("Average grade = %.1f\n" % (avegr))
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 numbers, as well as strings. The following code
starts with an empty string, and then adds to it each time through
the for loop
:
n = 10
output = ""
for i in range(n):
output = output + "*"
print(output)
Running the above code displays this:
*
**
***
****
*****
******
*******
********
*********
**********
Note: in the above for
loop, we are not really using the loop variable, i
.
We just use the loop to accumulate the string.
Write a program to ask the user for miles run each day of a week:
$ python runninglog.py
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
Here's a string accumulator problem. Ask the user for a string, then accumulate the string, reversing the letters:
$ python revstr.py
Text: we LOVE computer science!!
!!ecneics retupmoc EVOL ew