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

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

for building in ['Jefferson', 'Madison', 'Adams']:
print(place)
IndentationError: expected an indented block
first_name = "Thomas"
  last_name = "Jefferson"
  File "<ipython-input-7-f65f2962bf9c>", line 2
    last_name="Jefferson"
    ^
IndentationError: unexpected indent

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

for building in ['Jefferson', 'Madison', 'Adams']:
    print(building)

Loop variable names follow the normal variable name conventions.

For example, you wouldn’t want to do:

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

Show loop using pens exercise and include something that’s not a pen.

The body of a loop can contain many statements.

Math example:

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

Use range to iterate over a sequence of numbers.

for number in range(0,3):
    print(number)
0
1
2

Or use range to repeat an action an arbitrary number of times.

for number in range(5):
    print("Again!")
Again!
Again!
Again!
Again!
Again!

The Accumulator pattern turns many values into one.

Say we have the following list: sizes = [‘xs’,’s’,’m’,’l’,’xl’]

Use the string method .upper() Write a for statement to:

sizes = ['xs','s','m','l','xl']
upper_sizes = []

for s in sizes:
    new_size = s.upper()
    upper_sizes.append(new_size)

print(upper_sizes)
['XS', 'S', 'M', 'L', 'XL']

For loops become more powerful when we can start to do more to test the data.

Practice Accumulating

Key Points

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

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

  • Indentation is always meaningful in Python.

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

  • 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.