Overview
Teaching: 10 min Exercises: 10 minQuestions
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.
pressure_001
, pressure_002
, etc.for number in [2, 3, 5]:
print(number)
for
loop is equivalent to:print(2)
print(3)
print(5)
for
loop’s output is:2
3
5
for
loop must end with a colon, and the body must be indented.{}
or begin
/end
to show nesting.
for number in [2, 3, 5]:
print(number)
IndentationError: expected an indented block
for
loop is made up of a collection, a loop variable, and a body.for number in [2, 3, 5]:
print(number)
[2, 3, 5]
, is what the loop is being run on.print(number)
, specifies what to do for each value in the collection.number
, is what changes for each iteration of the loop.
for kitten in [2, 3, 5]:
print(kitten)
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
range
to iterate over a sequence of numbers.range
produces a sequence of numbers.
range(N)
is the numbers 0..N-1
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
# Sum the first 10 integers.
total = 0
for number in range(10):
total = total + (number + 1)
print(total)
55
total = total + (number + 1)
as:
number
.total
.total
, replacing the current value.number + 1
because range
produces 0..9, not 1..10.Classifying Errors
Is an indentation error a syntax error or a runtime error?
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 char in "tin": total = total + 1
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)
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)
# List of word lengths: ["red", "green", "blue"] => [3, 5, 4] lengths = ____ for word in ["red", "green", "blue"]: lengths = 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
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) data = [1,2,2,5]
Indentation Errors
What kind of error does Python report when we try to run the following program?
for char in 'helium': print char
Is this a syntax error or a runtime error?
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.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.