# Week 2, Monday: for loops, accumulator pattern

• lab 1 is due Saturday night
• unix knowledge: TAB key, up arrow/history
• vim knowledge: x gg G dd p 5G A

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:

• can chain function calls together (`int(raw_input("prompt: ")`)
• error messages (`SyntaxError: invalid syntax`) when missing a paren are often on the line above where the error message tells you to look!
• you don't have to use `sq` above, but sometimes it makes the code easier to read
• using the plus operator to put together that string is klunky (we will see a better way to do that on Wednesday of this week)

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:

• the accumulator variable (`output`) is initialized before the loop
• inside the loop, the accumulator variable is reassigned to be itself plus something (i.e., `output = output + char`, or `x = x + 1`)

Using an accumulator, can you write the following program?

``````\$ python average.py

``````