For Loops#

Learning Objectives

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.


How for loops work#

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

Doing calculations on the values in a list one by one is as painful and not very fast. Instead we can use a for loop.

  • A for loop tells Python to execute some statements once for each value in a list, a character string, or some other collection.

  • “For each thing in this group, do these operations.”

for animal in ["dog", "giraffe", "whale"]:
    print(animal)
Hide code cell output
dog
giraffe
whale

The for loop above is equivalent to:

print("dog")
print("giraffe")
print("whale")
Hide code cell output
dog
giraffe
whale
  • The variable name (here animal) is a name that you choose, when you create the for loop.

  • You can choose any variable name you want.

  • But do not use an already existing variable name, as this will then be overwritten.

  • The variable persists after the loop is done and will contain the last used value.

  • In the case above, animal will contain the string “whale” after the for loop is finished.


For loop syntax#

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

  • The colon at the end of the first line signals the start of a block of statements.

  • Python uses indentation to show nesting (rather than {} or begin/end, which are used in some other programming languages).

Any consistent indentation is legal, but almost everyone uses four spaces or tab. IDEs like Jupyter Lab will automatically create an indentation after the colon.

for animal in ["dog", "giraffe", "whale"]:
print(animal)
Hide code cell output
  Cell In[4], line 2
    print(animal)
    ^
IndentationError: expected an indented block after 'for' statement on line 1

Indentation is always meaningful in Python.

firstName = "Jon"
  lastName = "Smith"
Hide code cell output
  Cell In[5], line 2
    lastName = "Smith"
    ^
IndentationError: unexpected indent

This error can be fixed by removing the indentation at the beginning of the second line.


For loop structure#

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

for animal in ["dog", "giraffe", "whale"]:
    print(animal)
Hide code cell output
dog
giraffe
whale
  • The collection, ["dog", "giraffe", "whale"], is what the loop is being run on.

  • The loop variable, animal, is what changes for each iteration of the loop.

    • It “contains” dog in the first iteration, giraffe in the second iteration, and whale in the third iteration.

    • After the for loop is finished, animal still contains whale.

  • The body, print(animal), specifies what to do for each value in the collection.


Naming loop variables#

Loop variable names follow the normal variable name conventions.

Loop variables will:

  • Be created on demand during the course of each loop.

  • Often be used in the course of the loop.

  • Persist after the loop finishes.

So give them a meaningful name you will understand as the body code in your loop grows. Example: for single_letter in ['A', 'B', 'C', 'D']: instead of for asdf in ['A', 'B', 'C', 'D']:.

Use a new variable name to avoid overwriting a data collection you need to keep for later.


Multiple statements in a for loop#

The body of a loop can contain many statements.

  • You can have as much code as you like inside of a loop.

  • But keep in mind, the more code you have, the more difficult it can be to keep track of.

# List of pages read in a book of 200 pages
pages_read = [45, 120, 75]

# Loop through each book's pages read
for pages in pages_read:
    # Calculate the remaining pages
    pages_remaining = 200 - pages
    
    # Print the results
    print("For a book with", pages, "pages read so far,")
    print("Pages remaining to reach 200:", pages_remaining)
Hide code cell output
For a book with 45 pages read so far,
Pages remaining to reach 200: 155
For a book with 120 pages read so far,
Pages remaining to reach 200: 80
For a book with 75 pages read so far,
Pages remaining to reach 200: 125

Using range with the for loop#

We can use range to go through a sequence of numbers.

  • The built-in function range produces a sequence of numbers. Not a list: the numbers are produced on demand to make looping over large ranges more efficient.

  • range(N) is the numbers 0, 1, 2, … N-1

print('A range is not a list: range(0, 3)')
for number in range(0, 3):
    print(number)
Hide code cell output
A range is not a list: range(0, 3)
0
1
2

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

You do not actually have to use the iterable variable’s value. Use this structure to simply repeat an action some number of times.

That number of times goes into the range function.

for number in range(5):
    print("Again!")
Hide code cell output
Again!
Again!
Again!
Again!
Again!

Using accumulator variables#

A common pattern in programs is to:

  1. Initialize an accumulator variable to zero, the empty string, or the empty list.

  2. Update the variable with values from a collection.

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

Note

Notice, that we use number + 1.

This is because range(10) will go through the numbers from 0 up to but not including 10. I.e., from 0 to 9.

Read total = total + (number + 1) as:

  • Add 1 to the current value of the loop variable number.

    • We have to add number + 1 because range produces the numbers 0…9, not 1…10.

  • Add that to the current value of the accumulator variable total.

  • Assign that to total, replacing the current value.


Exercises#

Exercise 1: Classifying errors#

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


Exercise 2: 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

Exercise 3: Reversing a string#

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

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

Exercise 4: Fill in the blanks#

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)
# List of word lengths: ["red", "green", "blue"] => [3, 5, 4]
lengths = ____
for word in ["red", "green", "blue"]:
    lengths.____(____)
print(lengths)
# Concatenate all words: ["red", "green", "blue"] => "redgreenblue"
words = ["red", "green", "blue"]
result = ____
for ____ in ____:
    ____
print(result)
# Create acronym: ["red", "green", "blue"] => "rgb"
# write the whole thing

Exercise 5: Cumulative sum#

Reorder and properly indent the lines of code below so that they print an array with the cumulative sum of data. The cumulative sum is calculated by adding each number to the sum of all previous numbers.

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]

Exercise 6: 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)
Hide code cell output
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[12], line 3
      1 for number in range(10):
      2     # use a if the number is a multiple of 3, otherwise use b
----> 3     if (Number % 3) == 0:
      4         message = message + a
      5     else:

NameError: name 'Number' is not defined

Exercise 7: 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])
Hide code cell output
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[13], line 2
      1 seasons = ['Spring', 'Summer', 'Fall', 'Winter']
----> 2 print('My favorite season is ', seasons[4])

IndexError: list index out of range

Key points#

  • A for loop (for) 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.