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 i in range(5):

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:

Together, we will show in 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

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"


Open 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 
Task 1:
Enter first name: Tina
Enter last name: Fey

Welcome Tina Fey

Task 2:
There are 7 characters in your name

Task 3:
Initials: T.F.

Last initials: a.y.

Task 4: