For loops and how they compare with while loops.
Data 94, Spring 2021 @ UC Berkeley
Suraj Rampure, with help from many others
Iteration, Part 2
11
Overview
Announcements
For loops
Two types of loops
Loops allow us to repeat the execution of code.
There are two types of loops in Python. The while loop one of them, and the for loop is the other.
“While this condition is true, repeat this code.”
“For each element of this sequence, repeat this code.”
while <boolean expression>:
<while body>
for <elem> in <sequence>:
<for body>
A list is a sequence. So is a string.
For loops
This code is repeated 4 times: once for each element in the list [2, 4, 6, 8].
There is no “n = “ anywhere!
No need to increment (add one).
More for loops
The body of a for loop doesn’t have to involve the loop variable (i) – but it often does.
The loop variable can be anything you want it to be: n, i, verb, etc.
Example: fares
Suppose we have a data set of Titanic survivors, with information about the fare they paid.
Task: Write a function that, given a list of fares and a threshold, returns the number of fares that are above the threshold.
# Evaluates to 4, since 4 nums are >3
count_above([1, 2, 5, 8, 7, 9], 3)
# Evaluates to 0, since 0 nums are >10
count_above([4, 8, 2, 1], 10)
Using a while loop:
Using a for loop:
Blue: pieces that are different between the two implementations.
Orange: pieces that are no longer necessary in the for loop implementation.
Everything else is the same.
Quick Check 1
In one English sentence, what does the function not_sure do?
def not_sure(word):
output = ''
for letter in word:
if letter in 'aeiou':
output += letter
return output
For loops with strings
Just like we can iterate through each element of a list, we can iterate through each character of a string.
Range
Range
The function range creates a sequence of numbers.
Range examples
Example: adding lists
Suppose we have two lists, and want to add the elements in each list pairwise. Let’s define a function list_add to help us.
Idea: For each valid position i,
Quick Check 2
Fill in the two blanks so that the following code works as displayed.
Summary, next time
Summary
“While this condition is true, repeat this code.”
“For each element of this sequence, repeat this code.”
while <boolean expression>:
<while body>
for <elem> in <sequence>:
<for body>
A list is a sequence. So is a string.
Next time
Announcements