This lesson is in the early stages of development (Alpha version)

For Loops

Overview

Teaching: 20 min
Exercises: 20 min
Questions
  • How can I make a program repeat a task?

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 accumulator 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 number in [2, 3, 5]:
print(number)
    print(number)
    ^
IndentationError: expected an indented block after 'for' statement on line 1
firstName = "Jon"
  lastName = "Smith"
    lastName = "Smith"
    ^
IndentationError: unexpected indent

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

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

Loop variable names follow the normal variable name conventions

The body of a loop can contain many statements

numbers = [2, 3, 5]
for n in numbers:
    squared = n ** 2
    cubed = n ** 3
    print("The number", n, "squared is:", squared, ", and the number", n, "cubed is:", cubed)
The number 2 squared is: 4 , and the number 2 cubed is: 8
The number 3 squared is: 9 , and the number 3 cubed is: 27
The number 5 squared is: 25 , and the number 5 cubed is: 125

Use range to go through 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

Or use range to repeat an action a set number of times

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

Using accumulator variables

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

Exercises

Classifying Errors

Is an indentation error a syntax error or a runtime error?

Solution

It is a syntax error. The problem has to do with the placement of the code, not its logic.

Tracing Execution

Create a table showing the numbers of the lines that are executed when this program runs, and the values of the variables after each line is executed.

total = 0
for animal in ['cat', 'dog', 'elephant', 'fish']:
    total = total + 1

Solution

Code line # total animal
1 0 N/A
2 0 'cat'
3 1 'cat'
2 1 'dog'
3 2 'dog'
2 2 'elephant'
3 3 'elephant'
2 3 'fish'
3 4 'fish'

Explanation:

  • Line 1 initializes the variable total with a value of 0.
  • Line 2 begins a for loop that iterates over the list ['cat', 'dog', 'elephant', 'fish'].
    • Line 2 is the first iteration, where animal takes the value ‘cat’, and total retains 0.
    • Line 3 increments total by 1, making it 1, and animal retains the value ‘cat’.
    • Line 2 is the second iteration, where animal takes the value ‘dog’, and total retains 1.
    • Line 3 increments total by 1, making it 2, and animal retains the value ‘dog’.
    • Line 2 is the third iteration, where animal takes the value ‘elephant’, and total retains 2.
    • Line 3 increments total by 1, making it 3, and animal retains the value ‘elephant’.
    • Line 2 is the fourth iteration, where animal takes the value ‘fish’, and total retains 3.
    • Line 3 increments total by 1, making it 4, and animal retains the value ‘fish’.

After the program finishes, total is 4, and animal retains its value from the last iteration, which is ‘fish’.

Reversing a String

Fill in the blanks in the program below so that it prints “nit” (the reverse of the original character string “tin”).

original = "tin"
result = ____
for char in original:
    result = ____
print(result)

Solution

  • result is an empty string because we use it to build or accumulate on our reverse string.
  • char is the loop variable for original.
  • For each iteration of the loop, char takes on one value (character) from original.
  • Add char to the beginning of result to change the order of the string.
  • Our loop code should look like this:
original = "tin"
result = ""
for char in original:
   result = char + result
print(result)

If you were to explain the loop step by step, the iterations would look something like this:

#First loop
char = "t"
result = ""
char + result = "t"
#Second loop
char = "i"
result = "t"
char + result = "it"
#Third loop
char = "n"
result = "it"
char + result = "nit"

Practice Accumulating

Fill in the blanks in each of the programs below to produce the indicated result.

# Total length of the strings in the list: ["red", "green", "blue"] => 12
total = 0
for word in ["red", "green", "blue"]:
    ____ = ____ + len(word)
print(total)

Solution

# Total length of the strings in the list: ["red", "green", "blue"] => 12
total = 0
for word in ["red", "green", "blue"]:
    total = total + len(word)
print(total)
# List of word lengths: ["red", "green", "blue"] => [3, 5, 4]
lengths = ____
for word in ["red", "green", "blue"]:
    lengths.____(____)
print(lengths)

Solution

# List of word lengths: ["red", "green", "blue"] => [3, 5, 4]
lengths = []
for word in ["red", "green", "blue"]:
    lengths.append(len(word))
print(lengths)
# Concatenate all words: ["red", "green", "blue"] => "redgreenblue"
words = ["red", "green", "blue"]
result = ____
for ____ in ____:
    ____
print(result)

Solution

# Concatenate all words: ["red", "green", "blue"] => "redgreenblue"
words = ["red", "green", "blue"]
result = ""
for word in words:
    result = result + word
print(result)
# Create acronym: ["red", "green", "blue"] => "rgb"
# write the whole thing

Solution

acronym = ''
colours = ["red", "green", "blue"]
for colour in colours:
    acronym = acronym + colour[0]
print(acronym)

Cumulative Sum

Reorder and properly indent the lines of code below so that they print an array with the cumulative sum of data. The result should be [1, 3, 5, 10].

cumulative += [sum]
for number in data:
cumulative = []
sum += number
print(cumulative)
sum = 0
data = [1,2,2,5]

Solution

data = [1,2,2,5]
cumulative = []
sum = 0
for number in data:
  sum += number
  cumulative += [sum]
print(cumulative)
[1, 3, 5, 10]

Identifying Variable Name Errors

  1. Read the code below and try to identify what the errors are without running it.
  2. Run the code and read the error message. What type of NameError do you think this is? Is it a string with no quotes, a misspelled variable, or a variable that should have been defined but was not?
  3. Fix the error.
  4. Repeat steps 2 and 3, until you have fixed all the errors.
for number in range(10):
    # use a if the number is a multiple of 3, otherwise use b
    if (Number % 3) == 0:
        message = message + a
    else:
        message = message + "b"
print(message)

Identifying Item Errors

  1. Read the code below and try to identify what the errors are without running it.
  2. Run the code, and read the error message. What type of error is it?
  3. Fix the error.
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print('My favorite season is ', seasons[4])

Solution

It is an index error:

IndexError: list index out of range

The problem is that 4 points to an item that doesn’t exist in the list. Remember the first item of a list in Python is 0.
Replace seasons[4] with seasons[0], seasons[1], seasons[2] or seasons[3] to have the different items of the list printed.

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.