Week 2, Monday: for loops, accumulator pattern



Here is the squares.py program from last time:

"""
print out squares from 1 to n

J. Knerr
Fall 2015
"""

#########################################

def main():
  n = int(raw_input("end number: "))
  for i in range(1,n+1):
    sq = i*i
    print (str(i)+" x "+str(i)+" = "+str(sq))

#########################################

main()

A few things to note:

Here is the triangle program:

"""
print out a right-triangle to the screen, based on user input

J. Knerr
Fall 2015
"""

#########################################

def main():
  char  = raw_input("char: ")
  n = int(raw_input(" num: "))
  for i in range(n):
    print (char*(i+1))

#########################################

main()

The trick to for loops is finding or seeing the pattern. In this program, it prints 1 char, then 2, then 3, and so on, so the pattern is fairly obvious. If we have a for loop, where the variable increases by one each time, we should be able to print that many chars each time.

the accumulator pattern

How is this program different from the one above?

def main():
  char  = raw_input("char: ")
  n = int(raw_input(" num: "))
  output = char
  for i in range(n):
    print (output)
    output = output + char

It actually prints the same thing, but uses an accumulator to build up or add to the output string, each time through the for loop.

The interesting line is the last one: output = output + char. That seems odd to students that are still thinking of the equals sign mathematically. But it's not an equation, it's an assignment statement! And the computer does the right side, first (figure out what output + char is). Once it has a value for the right side, it assigns that value back to the variable on the left side. In the end, it just prints one char, then two, then three, and so on.

Note some important accumulator pattern points:

Using an accumulator, can you write the following program?

$ python average.py 

Number of grades: 5
grade: 90
grade: 92
grade: 88
grade: 100
grade: 95
Average grade = 93.0

This program first asks for the number of grades, then asks for each grade. At the end, it prints the average of those grades.

Note: if we knew more python, we might write this program a different way. For example, we could get each grade and store them in a list. Then, after getting the input, we could use the grades stored in the list to figure out the average grade.