# Reminders

• run handin21 before Saturday night
• See Office Hours if you have questions.
• Ninja Sessions are available Wed 7-10pm, Fri 7-9pm.

# Today

• Recap
• Accumulator Pattern
• repetition with for loops
• lists with the range function

## Repetition using for loops

Before Wednesday, all of our programs were sequential - with one line of code following the other. Often, we need to repeat a task several times. If we know the number of times, we use definite loops which are called for loops in Python. The syntax is:

for VAR in SEQUENCE:
BODY
for i in range(5):
print(n-i)

This semester, you will see many different kinds of for loops. We hope to give you some more experience/practice with for loops today.

## Accumulator Pattern

A very common use of loops is to aggregate, or combine, the result of a repetitive set of steps. For example, we may want to sum the numbers from 1 to n. To create an accumulator pattern, we should first answer these questions to help us code the solution:

• What are we accumulating? (should create a variable to store this)
• Where does the accumulator start? (initialize variable; not always 0)
• How many iterations/times do we loop? (use to set the range)
• What do we need to calculate inside the loop? How do we update the accumulator (updating the variable must be a part of the loop)
• What do we do with result of accumulation?

Together, we will show in avg.py how to use an accumulator pattern to average a series of numbers entered by a user.

### Exercise: factorial

Work with a neighbor and sketch out your solution to calculating the factorial of a number. Do not start to code until you have answered all of the questions above for designing an accumulation pattern. Your program should ask the user for a number (integer) and calculate the factorial. The factorial of a number is x!=x * (x − 1)*(x − 2)*...*2 * 1 e.g., 5!=5 * 4 * 3 * 2 * 1. Begin by answer the questions above and then start to write your program in factorial.py.

## More String Operations

You've seen several instances of strings already this semester, and you've likely used string concatenation to build up a string. There are many other useful string operations. Here are some highlights:

1. length. To get the length of a string, use the len command e.g. len("cs21") = 4
2. indexing. Access a single character in a string using its position indexing from zero. For example, if name="Punxsutawney", then name[1] = "u".
3. concatenation. Concatenate with the + operator. "hello" + "world" == "helloworld"

### Exercise: str_practice.py

Open str_practice.py to complete four tasks and a couple of extensions if you desire. Be sure to incrementally develop---complete one task, run your program to see if that tasks works, and then move onto the next. Tasks 4 and bonus will require for loops and accumulators.

\$ python3 str_practice.py
Enter first name: Tina
Enter last name: Fey

Welcome Tina Fey

a