1 of 18

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

2 of 18

Overview

Announcements

  • For loops.
    • How do they compare to while loops?
  • Range.
  • Examples.
  • Quiz 1 scores released! See this post on Ed for details.
    • No autograder: we graded things manually.
    • Scores out of 9, not 12 or 15.
    • Submit regrades by next Monday if you have any concerns!
  • Homework 2 due tonight.
    • OH today from 2-4PM.
  • Homework 3 released tomorrow.

3 of 18

For loops

4 of 18

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.

5 of 18

For loops

This code is repeated 4 times: once for each element in the list [2, 4, 6, 8].

  • In the first iteration, n is 2.
  • In the second iteration, n is 4.
  • In the third iteration, n is 6.
  • In the fourth iteration, n is 8.

There is no “n = anywhere!

No need to increment (add one).

6 of 18

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.

7 of 18

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)

8 of 18

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.

9 of 18

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

10 of 18

For loops with strings

Just like we can iterate through each element of a list, we can iterate through each character of a string.

11 of 18

Range

12 of 18

Range

The function range creates a sequence of numbers.

  • range() creates a value whose type is “range” – not list! To convert a range to a list, use list().
  • list(range(n)) is a list of all integers from 0 to n-1.
  • list(range(start, stop)) is a list of all integers from start to stop-1.
  • list(range(start, stop, d)) is a list of integers from start to stop-1, counting by d.
  • range()works a lot like indexing – inclusive of the starting position, exclusive of the ending position.

13 of 18

Range examples

14 of 18

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.

  • For example, list_add([1, 2, 3], [4, 5, 6]) should evaluate to [5, 7, 9].
  • If the lists have different lengths, this doesn’t really make sense.

Idea: For each valid position i,

  1. Add a[i] and b[i].
  2. Append the result to an output list.

15 of 18

Quick Check 2

Fill in the two blanks so that the following code works as displayed.

16 of 18

Summary, next time

17 of 18

Summary

  • For loops perform one iteration for each element of a list, string, or range.
    • While loops, on the other hand, perform iterations as long as some boolean condition is true.
  • For loops have more straightforward and concise syntax when dealing with lists.

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

18 of 18

Next time

Announcements

  • More examples with for loops.
  • Time permitting: 2D lists and nested for loops.
  • Quiz 1 scores released! See this post on Ed for details.
    • No autograder: we graded things manually.
    • Scores out of 9, not 12 or 15.
    • Submit regrades by next Monday if you have any concerns!
  • Homework 2 due tonight.
    • OH today from 2-4PM.
  • Homework 3 released tomorrow.