For Loops

Overview

Teaching: 10 min
Exercises: 15 min
Questions
  • How can I make a program do many things?

Objectives
  • Explain what for loops are normally used for.

  • Trace the execution of a simple (unnested) loop and correctly state the values of variables in each iteration.

  • Write for loops that use the Accumulator pattern to aggregate values.

A for loop executes commands once for each value in a collection.

for number in [2, 3, 5]:
    print(number)
print(2)
print(3)
print(5)
2
3
5

A for loop is made up of a collection, a loop variable, and a body.

for number in [2, 3, 5]:
    print(number)

The first line of the for loop must end with a colon, and the body must be indented.

for number in [2, 3, 5]:
print(number)
IndentationError: expected an indented block
firstName="Jon"
  lastName="Smith"
  File "<ipython-input-7-f65f2962bf9c>", line 2
    lastName="Smith"
    ^
IndentationError: unexpected indent

Loop variables can be called anything.

for kitten in [2, 3, 5]:
    print(kitten)

The body of a loop can contain many statements.

primes = [2, 3, 5]
for p in primes:
    squared = p ** 2
    cubed = p ** 3
    print(p, squared, cubed)
2 4 8
3 9 27
5 25 125

Let’s visualize this loop using Python Tutor. In the notebook, write

%load tutor.py

This loads the following code:

from metakernel import register_ipython_magics
register_ipython_magics()

Execute the code (it gives no output).

Now you can rerun the previous for loop in a new cell that starts with %%tutor:

%%tutor
primes = [2, 3, 5]
for p in primes:
    squared = p ** 2
    cubed = p ** 3
    print(p, squared, cubed)

Use range to iterate over a sequence of numbers.

print('a range is not a list: range(0, 3)')
for number in range(0,3):
    print(number)
a range is not a list: range(0, 3)
0
1
2

A string is also a collection that can be looped over.

organ = "liver"
for char in organ:
    print(char)

This means that if we have a DNA string, we can loop over the individual bases:

DNA = "ACGTGC"
for base in DNA:
    print(base)

As an example, let’s use a for loop to de the same as the .upper() function. .upper() changes all characters to upper case:

dna1 = "acgtgc"
print(dna1)
dna2 = dna1.upper()
print(dna2)

With a for loop, we could do it like this:

dna1 = "acgtgc"
dna2 = ''
print(dna1)
for base in dna1:
    dna2 = dna2 + base.upper()
print(dna2)

Rerun this loop using Python Tutor as described above.

The Accumulator pattern turns many values into one.

# Sum the first 10 integers.
total = 0
for number in range(10):
   total = total + (number + 1)
print(total)
55

Exercises on slides

Key Points

  • A for loop executes commands once for each value in a collection.

  • A for loop is made up of a collection, a loop variable, and a body.

  • The first line of the for loop must end with a colon, and the body must be indented.

  • Indentation is always meaningful in Python.

  • Loop variables can be called anything (but it is strongly advised to have a meaningful name to the looping variable).

  • The body of a loop can contain many statements.

  • Use range to iterate over a sequence of numbers.

  • The Accumulator pattern turns many values into one.