6: Iteration

Contents

6: Iteration#

What are loops and why should we care about them?#

Loops are a fundamental building block of computational solutions to problems. They, like conditionals, are an example of control flow: structures in our program that control what happens when. Recall that control flow allows you to control when/whether (conditional) and how many times (loops) you do things

Loops are especially useful because it’s hard to build programs without a concise way to instruct the computer to do repeated actions.

Here are some simple examples. Try to think of how you might solve these without loops!

  • Put 6 cups of flour into a box

  • Stir occasionally until the sauce starts to reduce

With loops these get a LOT easier to specify, and become more robust and reusable too.

Example (not real!) program: Put 6 cups of flour into a box

1def scoop_into_box():
2    print("Scoop into box")
3
4# scoop into the box 6 times
5for i in range(6):
6    scoop_into_box()
Scoop into box
Scoop into box
Scoop into box
Scoop into box
Scoop into box
Scoop into box

Example (not real!) program: Stir occasionally until the sauce starts to reduce (i.e., is thick)

1# stir the sauce until it is thick
2while check_sauce() != "thick":
3    stir()

Loops also enable many useful algorithms/patterns that go nicely with lists. You’ll be practicing and applying them in PCEs and Projects this module!

For example:

  • Searching through a list

  • Filtering a list of items

  • Counting occurrences in some collection

Continuing with our running example for this module, here are loops in the context of a program:

 1# key variables:
 2# the input LIST of strings
 3inputs = [
 4    "hello sarah@umd.edu",
 5    "from: joelchan@umd.edu",
 6    "some other text that doesn't have an email"
 7]
 8# a LIST to store the email addresses
 9emails = []
10
11# LOOP over every text input
12for text_input in inputs:
13
14    # extract an email address
15    # split the text into subsets
16    chunks = text_input.split()
17
18    # LOOP over the list of chunks to check each one
19    for chunk in chunks:
20        # check if it has @ and .
21        if "@" in chunk and "." in chunk:
22            # put the chunk in the email list
23            emails.append(chunk)
24# give the email address back to the user
25print(emails)
['sarah@umd.edu', 'joelchan@umd.edu']

Definite loops (for loops)#

Quite often we have a list of items of the lines in a file - effectively a finite set of things. We can write a loop to do some operation once for each of the items in a set using the Python for construct.

These loops are called “definite loops” because they execute an exact number of times. We say that “definite loops iterate through the members of a set”

Use definite/for when you know in advance how many times you want to do something.

This is the use case in our running example.

Other examples:

  • Do an action N times

  • Take M steps

  • Do something for every item in a finite list

Anatomy of a definite (for) loop in Python#

Let’s take a closer look.

  • The iteration variable “iterates” through the sequence (ordered set)

  • The block (body) of code is executed once for each value in the sequence

  • The iteration variable moves through all of the values in the sequence

 1nums = [5, 4, 3, 2, 1]
 2# here, n is the iteration variable
 3
 4n = nums[0]
 5n = nums[1]
 6n = nums[2]
 7
 8for n in nums:
 9    print("taking something from the list")
10    print(n) # block/body
taking something from the list
5
taking something from the list
4
taking something from the list
3
taking something from the list
2
taking something from the list
1
1nums = [5, 4, 3, 2, 1]
2# here, i is the iteration variable
3for i in nums:
4    print(i)
5    new_num = i*20
6    print(new_num) # block/body
5
100
4
80
3
60
2
40
1
20

The iteration variable is a variable: this means you can name it whatever you like, subject to the basic syntax rules and of course our heuristic to name things to make the logic of the program legible.

What is the iteration variable here?

1nums = [5, 4, 3, 2, 1]
2for a_number in nums:
3    new_num = a_number*20
4    print(new_num) # block/body
100
80
60
40
20

What is the iteration variable here?

1nums = [5, 4, 3, 2, 1]
2for num in nums:
3    if num % 2 == 0: # check if even
4        print(num) # block/body
4
2

What is the iteration variable here?

1for name in ["john", "terrell", "qian", "malala"]:
2    print(name)
john
terrell
qian
malala

PRACTICE: print out each name in this list

1names = ["Joel", "John", "Jane", "Jamie", "John", "Michael", "Sarah", "Joseph", "Chris", "Ray"]
2
3# your loop here

PRACTICE: print out each donation in this list

1donations = [
2    0.00, 10.00, 25.00, 50.00, 75.00, 100.00, 250.99, 500.00, 1000.00, 2500.00,
3    5000.00, 7500.50, 10000.00, 0.00, 12500.75, 15000.00, 20000.99, 25000.00, 30000.00,
4    40000.00, 50000.00, 243.29, 0.00
5]
6
7
8# your loop here

Iterating a set number of times#

So far we’ve looked at examples of iterating through a list of definite length (usually do something with each element in the list, in order). We also often use definite loops to do some action(s) a set number of times.

In these situations, instead of iterating through an existing list, we use the range() function to generate a collection of length n that we can iterate through to do something n times. We usually don’t do anything with the elements of that collection, except maybe to keep count of how many times we’ve done the thing.

Here’s an example:

1# use this if you want to specify doing something N times
2# e.g., here, take a step 5 times
3for i in range(5):
4    print("I has the value", i)
5    print("Taking a step")
I has the value 0
Taking a step
I has the value 1
Taking a step
I has the value 2
Taking a step
I has the value 3
Taking a step
I has the value 4
Taking a step

Under the hood, range() is taking the argument 5, which means it will generate a collection starting at 0 (this is the default behavior, which you can change if you like), and ending before 5 (i.e., it creates a collection that contains, in order, the elements 0, 1, 2, 3, 4). Note that this collection has 5 elements in it. Since the loop does something for each item in this collection, it will do that something (in this case, printing those two statements in the body of the loop) 5 times.

You can peek at what range() produces by turning it into a list:

1# range() produces a sequence of numbers that starts at the optional
2# first argument (0 if you leave it out) and stops *before* the stop argument.
3# with one argument, like range(5), that one argument is the stop.
4# https://www.w3schools.com/python/ref_func_range.asp
5list(range(0,5))
[0, 1, 2, 3, 4]

In this way, it’s quite similar to doing something like this (iterating through a list that contains elements running from 0 to 4).

1# use this if you want to specify doing something N times
2# e.g., here, take a step 5 times
3for i in [0,1,2,3,4]:
4    print("I has the value", i)
5    print("Taking a step")
I has the value 0
Taking a step
I has the value 1
Taking a step
I has the value 2
Taking a step
I has the value 3
Taking a step
I has the value 4
Taking a step

Since range() is a function, it can also accept a variable as an argument.

1# scoop 6 cups
2steps = 6
3for step in range(steps):
4    print("scooping cup number", step+1)
scooping cup number 1
scooping cup number 2
scooping cup number 3
scooping cup number 4
scooping cup number 5
scooping cup number 6

PRACTICE: how would you write a loop to print “hello” 3 times?

1# practice: your code here

To get a feeling for what is going on, try copy-pasting one of these programs into python tutor and inspect it!

Practice: Code Tracing with Definite Loops#

For each problem below, predict what the code will print before running the cell.

Trace 1#

1for i in range(4):
2    print(i)

What does this print?

  • A) 1 2 3 4

  • B) 0 1 2 3

  • C) 0 1 2 3 4

  • D) 1 2 3

Answer:

B) 0 1 2 3 (each on its own line)

range(4) produces 0, 1, 2, 3 — it starts at 0 and stops before 4. If you picked A, remember that range starts at 0 by default. If you picked C, remember the upper bound is exclusive.

Trace 2#

1count = 0
2for item in ["a", "b", "c", "d", "e"]:
3    count = count + 1
4print(count)

What does this print?

  • A) 4

  • B) 5

  • C) e

  • D) 0

Answer:

B) 5

The loop runs once per item in the list (5 items), and each time it increments count by 1. Note that print(count) is outside the loop (not indented under for), so it only prints the final value. If you picked A, you may be thinking range stops before the end — but this loop iterates over a list directly, once per item.

Trace 3#

1total = 0
2for num in [10, 20, 30]:
3    total = total + num
4    print(total)

What does this print?

  • A) 60

  • B) 10 20 30

  • C) 10 30 60

  • D) 0 10 30

Answer:

C) 10, 30, 60 (each on its own line)

total starts at 0. After the first iteration: 0 + 10 = 10. After the second: 10 + 20 = 30. After the third: 30 + 30 = 60. Because print(total) is inside the loop, it prints the running total each time. If you picked A, that’s what you’d get if the print were outside the loop.

Trace 4#

1for i in range(3):
2    print("hello")
3print("done")

What does this print?

  • A) hello once, then done

  • B) hello three times, then done

  • C) hello three times (no done)

  • D) hello four times, then done

Answer:

B) hello three times, then done

range(3) gives 0, 1, 2 — three values, so the loop body runs 3 times. print("done") is outside the loop (not indented), so it runs once after the loop finishes. If you picked C, look at the indentation — print("done") is at the same level as for, not inside the body.

Trace 5#

1result = []
2for n in [3, 1, 4]:
3    result.append(n * 2)
4print(result)

What does this print?

  • A) [3, 1, 4]

  • B) [6, 2, 8]

  • C) [6]

  • D) [8]

Answer:

B) [6, 2, 8]

Each iteration multiplies the current item by 2 and appends it to result. So: 3*2=6, 1*2=2, 4*2=8. If you picked C or D, remember the loop runs for every item in the list, not just the first or last.

Trace 6#

1for i in range(1, 6):
2    print(i)

What does this print?

  • A) 0 1 2 3 4 5

  • B) 1 2 3 4 5

  • C) 1 2 3 4 5 6

  • D) 0 1 2 3 4

Answer:

B) 1 2 3 4 5 (each on its own line)

range(1, 6) starts at 1 and stops before 6. If you picked C, remember the upper bound is always exclusive. If you picked A, note that the first argument changes the start from the default of 0.

Trace 7#

1x = 10
2for i in range(3):
3    x = x - i
4print(x)

What does this print?

  • A) 10

  • B) 7

  • C) 4

  • D) 1

Answer:

B) 7

Trace it step by step: i=0: x = 10 - 0 = 10. i=1: x = 10 - 1 = 9. i=2: x = 9 - 2 = 7. The print is outside the loop, so only the final value 7 is printed. The tricky part is that i changes each iteration (0, 1, 2), and x carries forward.

Trace 8#

1words = ["hi", "there", "world"]
2for word in words:
3    if len(word) > 3:
4        print(word)

What does this print?

  • A) hi there world

  • B) there world

  • C) there

  • D) Nothing (no output)

Answer:

B) there and world (each on its own line)

The loop checks each word’s length. "hi" has length 2 (not > 3, skipped). "there" has length 5 (printed). "world" has length 5 (printed). If you picked C, you may have thought > means “strictly greater” and "world" is exactly 5 — but 5 > 3 is True!

Trace 9#

1nums = [5, 10, 15, 20]
2for i in range(len(nums)):
3    print(i, nums[i])

What does this print?

  • A) 5 10 15 20

  • B) 0 5, 1 10, 2 15, 3 20

  • C) 1 5, 2 10, 3 15, 4 20

  • D) 0 10, 1 15, 2 20

Answer:

B) 0 5, 1 10, 2 15, 3 20 (each pair on its own line)

range(len(nums)) is range(4), which gives 0, 1, 2, 3. Each iteration, i is the index and nums[i] is the value at that index. This is the index-based iteration pattern — useful when you need both the position and the value.

Trace 10#

1result = ""
2for letter in ["P", "y", "t", "h", "o", "n"]:
3    result = result + letter
4print(result)
5print(len(result))

What does this print?

  • A) P y t h o n and 6

  • B) Python and 6

  • C) n and 1

  • D) Python and 11

Answer:

B) Python and 6

String concatenation (+) joins without spaces. Each iteration adds one letter to result: "" → "P" → "Py" → "Pyt" → … → "Python". The final string has 6 characters. This is the accumulator pattern — building up a result across iterations, just like accumulating a sum, but with strings instead of numbers.

Common design patterns with definite loops#

Counting#

A common situation: you have a list of stuff, and you want to count how many times a certain kind of thing shows up in that list.

If you want to count occurrences based on a simple exact match, you can use the .count() list method.

1names = ["Joel", "John", "Jane", "Jamie", "John", "Michael", "Sarah", "Joseph", "Chris", "Ray"]
2# count how many times "John" is in here
3names.count("John")
2

But often you want to count based on something more complex than an exact match. For example, let’s say I want to count the number of “high performers” in a list of scores (where high performing means score of 95 or greater).

Iteration is a really helpful way to do this.

Here’s an example program for counting how many scores are above a user-defined threshold.

 1#
 2scores = [65, 78, 23, 97, 100, 25, 95] # input list
 3
 4threshold = 67 # score of C
 5
 6n_highperformers = 0 # define the count variable, initialize to 0
 7
 8# go through each item
 9for score in scores:
10    # check if meets my criteria for being counted
11    if score >= threshold:
12        # if so, increase count
13        n_highperformers += 1
14print(n_highperformers)
4

The generic pattern (or algorithm) is something like this:

1# initialize count variable
2
3# for every item in list
4    # check if meets my criteria for being counted
5        # if so, increase count

Here’s an incomplete code template you can adapt and reuse:

1# initialize count variable
2count = 0 # we usually start at 0
3
4# for every item in list
5for item in some_list: # replace some_list with the actual list
6    # check if meets my criteria for being counted
7    if ____: # replace ____ with your actual Boolean expression to check the criteria
8        # if so, increase count
9        count = count + 1 # we usually increase the count by 1

You’ll often see count = count + 1 written as count += 1 (like in the example above). It’s a shorthand that means exactly the same thing: add 1 to the current value of count and store the result back in count.

PRACTICE: count how many “small dollar donors” (less than 100) or “big dollar donors” (1000 or up) are in this list of donations. Be careful! 0 is not a small dollar donation!

1donations = [
2    0.00, 10.00, 25.00, 50.00, 75.00, 100.00, 250.99, 500.00, 1000.00, 2500.00,
3    5000.00, 7500.50, 10000.00, 0.00, 12500.75, 15000.00, 20000.99, 25000.00, 30000.00,
4    40000.00, 50000.00, 243.29, 0.00
5]

PRACTICE: count how many names are short (e.g., 4 characters or less)? Or long (e.g., more than 5 characters).

1names = ["Joel", "John", "Jane", "Jamie", "Johnny", "Michaela", "Sarah", "Joseph", "Chris", "Ray"]
2
3# your code here

PRACTICE: check how many times we have a “banned” name. hint: how do we check if an item is in a list?

1names = ["Joel", "John", "Jane", "Jamie", "Johnny", "Michaela", "Sarah", "Joseph", "Chris", "Ray"]
2
3banned = ["Joel", "Chris"]
4
5# your code here

Filtering#

A closely related situation is where we want to not only count, but also “grab” or filter the things that meet our criteria.

We’d want to create a new list, and make sure we have a bit of code that adds to that new list based on the criteria we have.

Example: grab all scores that cross our threshold.

 1scores = [65, 82, 23, 97, 100, 95] # input list to be filtered
 2
 3threshold = 93 # the criterion
 4
 5# initialize empty list to hold filtered items
 6to_grab = []
 7
 8# go through each item
 9for score in scores:
10    # check if item meets criteria for being filtered
11    if score >= threshold:
12        # if so, add the item to the output list
13        to_grab.append(score)
14
15print(to_grab)
[97, 100, 95]

The generic pattern is something like this:

1# initialize empty list to hold filtered items
2
3# go through each item
4    # check if item meets criteria for being filtered
5        # if so, add the item to the output list

Here’s an incomplete code template you can adapt and reuse:

1# initialize empty list to hold filtered items
2filtered_list = [] # we usually start the list empty
3
4# for every item in list
5for item in some_list: # replace some_list with the actual list
6    # check if meets my criteria for being kept
7    if ____: # replace ____ with your actual Boolean expression to check the criteria
8        # if so, add the item to the output list
9        filtered_list.append(item)

PRACTICE: Let’s modify our program above to grab the small dollar donations and put them in a new list so we can count how many we have and what the total and average small dollar donation is.

1donations = [
2    0.00, 10.00, 25.00, 50.00, 75.00, 100.00, 250.99, 500.00, 1000.00, 2500.00,
3    5000.00, 7500.50, 10000.00, 0.00, 12500.75, 15000.00, 20000.99, 25000.00, 30000.00,
4    40000.00, 50000.00, 243.29, 0.00
5]

PRACTICE: Let’s modify our program above to grab only the names that aren’t in our banned list.

1names = ["Joel", "John", "Jane", "Jamie", "Johnny", "Michaela", "Sarah", "Joseph", "Chris", "Ray"]
2
3banned = ["Joel", "Chris"]
4
5# your code here

Just a reminder that you can use the filter() function if you’re curious, BUT YOU DO NOT HAVE TO. This is just an extra thing if you’re curious

1scores = [65, 82, 23, 97, 100, 95] # input list to be filtered
2threshold = 80
3
4def meets_critera(x):
5    return x >= threshold
6
7to_grab = list(filter(meets_critera, scores))
8print(to_grab)
[82, 97, 100, 95]

Mapping / transforming#

Finally, sometimes you want to modify some/all elements in a list into a new list. An example might be data cleaning, or data transformation.

EXAMPLE: Convert a list of scores (on scale of 0 to 100) to proportions.

 1# input list
 2scores = [65, 82, 23, 97, 100, 95]
 3
 4# output list
 5proportions = []
 6
 7# go through every item
 8for score in scores:
 9    # apply the transformation
10    proportion = score/100
11    # add the transformed value to the output list
12    proportions.append(proportion)
13proportions
[0.65, 0.82, 0.23, 0.97, 1.0, 0.95]

A variant of the program that’s a bit more concise (does the same thing):

 1# input list
 2scores = [65, 82, 23, 97, 100, 95]
 3
 4# output list
 5proportions = []
 6
 7# go through every item
 8for score in scores:
 9    # apply the transformation
10    # add the transformed value to the output list
11    proportions.append(score/100)
12proportions
[0.65, 0.82, 0.23, 0.97, 1.0, 0.95]

The generic pattern is something like this

1# initialize empty list to hold transformed items
2
3# go through each item in the input list
4    # apply transformation to item
5    # add transformed item to transformed items list

Here’s an incomplete code template you can adapt and reuse:

1# initialize empty list to hold transformed items
2transformed_list = [] # we usually start the list empty
3
4# for every item in list
5for item in some_list: # replace some_list with the actual list
6    # apply the transformation
7    transformed_item = item # replace the right hand side with an expression that modifies the item somehow
8    # and add the transformed item to the output list
9    transformed_list.append(transformed_item)

PRACTICE: Change outliers (those above 1000) to missing (“NA”)

1scores = [65, 82, 2323, 97, 100, 95000]
2
3# your code here

PRACTICE: Change the list from scores to letter grades, using the score to letter grade mappings from our syllabus (e.g., 93 and above is A).

1scores = [65, 82, 23, 97, 100, 95] # input list to be filtered
2
3# your code here

As an extra thing to try, you can use the map() built-in function to do this too!

1scores = [65, 82, 23, 97, 100, 95]
2# convert to proportions
3proportions = list(map(lambda x: x/100, scores))
4proportions
[0.65, 0.82, 0.23, 0.97, 1.0, 0.95]
 1def score_to_grade(a_score):
 2    # apply transformation to item
 3    if a_score >= 93:
 4        grade = "A"
 5    elif a_score >= 83:
 6        grade = "B"
 7    elif a_score >= 73:
 8        grade = "C"
 9    elif a_score >= 63:
10        grade = "D"
11    else:
12        grade = "F"
13    return grade
14
15scores = [65, 82, 23, 97, 100, 95]
16# convert to letter grades
17grades = list(map(score_to_grade, scores))
18grades
['D', 'C', 'F', 'A', 'A', 'A']

Coordinated iteration across one or more sequences#

How do you go through the elements of a list, index by index?

In our for loops above that iterated through items in a list, we typically had an iteration variable that directly stored an item from the list at each step.

But we can also define an iteration variable that iterates through a list of indices (remember what indices are in a list? they’re positions in the list!). This will allow us to then use Indexing to grab an item from that index position from our target list.

Here’s an example:

1scores = [65, 82, 23, 97, 100, 95]
2
3# iterate through a list of indices that is of the same length as the `scores` list
4# by convention, people usually name the iteration variable `i`
5for i in range(len(scores)):
6    # and print the score at that index
7    print(scores[i])
65
82
23
97
100
95

And another one:

 1# basic iteration through a list using indices
 2names = ["Joel", "John", "Lane", "Jamie", "Freddy"]
 3
 4# make a list of numbers that start at 0, and stop before
 5# the length of the names list
 6# and go through every number in that list
 7for index in range(len(names)):
 8    # use the number as an index for the names list
 9    name = names[index]
10    # do something with the item at that index
11    print(name)
Joel
John
Lane
Jamie
Freddy

We can extend this pattern to iterate through multiple lists at the same time in a coordinated way. This works as long as the lists are all of the same length: we’ll only need to define a list of indices that are the same length as one of the lists and avoid running into an IndexError (e.g., trying to grab an item from an index position that doesn’t exist from one of the lists that is shorter than the others!)

Here’s an example:

 1# basic iteration through a list using indices
 2names = ["Joel", "John", "Lane", "Jamie", "Freddy"]
 3eligibilities = [True, False, True, True, False]
 4
 5# make a list of numbers that start at 0, and stop before
 6# the length of the names list
 7# and go through every number in that list
 8for index in range(len(names)):
 9    # use the number as an index for the first list
10    name = names[index]
11    # use the same number as an index for the second list
12    eligible = eligibilities[index]
13    # do something with the items at the same index position for both lists
14    print(name, eligible)
Joel True
John False
Lane True
Jamie True
Freddy False

The generic pattern is something like this:

1# make a list of numbers that start at 0, and stop before
2# the length of one of the lists (assuming they are the same length!)
3# and go through every number in that list
4    # use the number as an index for the first list
5    # use the same number as an index for the second list
6    # do something with the items at the same index position for both lists

Here’s an incomplete code template you can adapt and reuse:

 1# make a list of numbers that start at 0, and stop before
 2# the length of one of the lists (assuming they are the same length!)
 3# and go through every number in that list
 4n = len(list_a) # set n to length of one of the lists
 5for i in range(n):
 6    # use the number as an index for the first list
 7    item_a = list_a[i]
 8    # use the same number as an index for the second list
 9    item_b = list_b[i]
10    # do something with the items at the same index position for both lists

One of problems for Project 2 (the rock paper scissors problem) relies on precisely this design pattern, since you need to go through two lists of moves in lockstep (first move from both players, then second move from both players, and so on).

Indefinite loops (while loops)#

Sometimes you want to repeat actions, but you don’t know in advance how many times you want to repeat. But you do have a clear idea of when to stop. In this situation, you can use indefinite loops.

Examples:

  • Keep going until I tell you to stop

  • Keep stirring until the sauce thickens

  • Keep taking candy from the box until your bucket is full or the box is empty

Use indefinite/while when you don’t know in advance how many times you want to do something, but can clearly express when to stop.

Notice that these examples are all phrased as stopping rules (“until…”). But a while line needs to have the opposite: a keep-going rule (“as long as…”). So you usually have to flip the stopping rule before you can write it in Python. When you flip it, each part gets negated, and an or becomes an and:

  • Stop when: your bucket is full or the box is empty

  • Keep going as long as: your bucket is not full and the box is not empty

Why does or become and? Any one reason is enough to stop. But to keep going, all of the reasons to stop have to be absent.

A good habit: always read a while line out loud as “keep going as long as…”.

Anatomy of an indefinite (while) loop in Python#

The while loop checks a condition before each iteration. The loop keeps running as long as the condition is True, and stops as soon as it becomes False.

  • The condition is a Boolean expression that controls whether the loop continues

    • while steps < limit: → keep going as long as steps is under the limit

    • while not found: → keep going as long as we haven’t found it yet

    • In both cases, the loop stops when the expression evaluates to False

  • The block (body) of code is executed once for each iteration in the loop

  • Condition update: It is essential that the body of the loop does something that can eventually make the condition False — otherwise the loop runs forever!

 1# keep taking steps until you hit a limit
 2steps = 0
 3limit = 10
 4# condition: keep going as long as steps is under the limit
 5while steps < limit:
 6    # body of the loop (aka do some stuff)
 7    print("Taking a step", steps)
 8    # update: bring steps closer to limit so the condition eventually becomes False
 9    steps += 1
10print("Done!")
Taking a step 0
Taking a step 1
Taking a step 2
Taking a step 3
Taking a step 4
Taking a step 5
Taking a step 6
Taking a step 7
Taking a step 8
Taking a step 9
Done!

Notice how this is similar to a for loop — the same stepping logic can be written either way:

1# the same thing with a for loop
2for i in range(10):
3    print("Taking a step", i)
4print("Done!")
Taking a step 0
Taking a step 1
Taking a step 2
Taking a step 3
Taking a step 4
Taking a step 5
Taking a step 6
Taking a step 7
Taking a step 8
Taking a step 9
Done!

The difference is that the for loop handles the counter (i) automatically, while the while loop requires you to initialize and update steps yourself. Use while when you don’t know in advance how many iterations you need.

Generic pattern:

1# initialize variables
2
3while condition:
4    # body of the loop (aka do some stuff)
5    # update something so the condition eventually becomes False

Here’s a guessing game example. This code uses input(), so it needs to be run interactively (e.g., copy-paste into a Python terminal):

 1guess = input("Try to guess the number between 1 and 10, or say `exit` to quit")
 2number = 5
 3found = False
 4
 5while guess != "exit" and not found:
 6    if int(guess) == number:
 7        print("You got it!")
 8        found = True
 9    else:
10        guess = input("Try to guess the number between 1 and 10, or say `exit` to quit")

Again, it’s helpful to copy-paste one of these programs into python tutor to get an intuition for what is going on.

Some applications of indefinite loops#

Generically: keep doing something until…#

Keep adding characters to a string until it is a defined length, e.g., 10

 1input_string = "abc"
 2
 3# while condition: keep going as long as...
 4while len(input_string) < 10:
 5    # body of the loop (aka do some stuff)
 6    input_string = input_string + "a"
 7    print(input_string)
 8    # the condition update is built in: we're modifying input_string, which is what the while checks
 9
10print(input_string)
11print(len(input_string))
abca
abcaa
abcaaa
abcaaaa
abcaaaaa
abcaaaaaa
abcaaaaaaa
abcaaaaaaa
10

Keep adding “.” to the string until it is 13 characters long.

1input_string = "abc"
2
3# while condition: keep going as long as...
4while len(input_string) < 13:
5    # body of the loop (aka do some stuff)
6    input_string = input_string + "."
7    # the condition update is built in: we're modifying input_string, which is what the while checks
8
9print(input_string)
abc..........

PRACTICE: Keep dividing a number by 2 (using integer division //) until the result is 0.

1num = 12000
2
3# your code here

Answer:

1while num > 0:
2    num = num // 2
3    print(num)

Reading the condition out loud: keep going as long as num is above 0. The line num = num // 2 is the update that brings us closer to stopping. The last value printed is 0, because the condition only gets checked at the top of the loop, after num has already become 0.

PRACTICE: Go through a list of people until we have 2 people named “John”.

1names = ["Joel", "John", "Jane", "Jamie", "John", "Michaela", "Sarah", "John", "Chris", "John"]
2
3# your code here

Answer:

1john_count = 0
2i = 0
3while john_count < 2 and i < len(names):
4    print(names[i])
5    if names[i] == "John":
6        john_count += 1
7    i += 1

This prints Joel, John, Jane, Jamie, John, and then stops. The i < len(names) part protects us if the list doesn’t have 2 Johns. Without it, i would run past the end of the list and we’d get an IndexError.

Basic user interfaces: keep running program until user stops us#

Guessing game. This code uses input(), so it needs to be run interactively (e.g., copy-paste into a Python terminal):

 1guess = input("Try to guess the number between 1 and 10, or say `exit` to quit")
 2number = 5
 3found = False
 4
 5while guess != "exit" and not found:
 6    if int(guess) == number:
 7        print("You got it!")
 8        found = True
 9    else:
10        guess = input("Try to guess the number between 1 and 10, or say `exit` to quit")
11print("Thanks for playing!")

Notice how we use two conditions joined by and: the loop keeps going as long as the user hasn’t typed “exit” AND we haven’t found the number yet. Either condition becoming False will stop the loop.

Later in this chapter we’ll learn about break, which gives us another way to exit a loop early.

All of the definite loops we saw earlier can be implemented with indefinite loops!#

 1# input list
 2scores = [65, 82, 23, 97, 100, 95]
 3
 4# output list
 5proportions = []
 6
 7# initialize index variable
 8i = 0
 9# while condition: keep going as long as...:
10# i is less than the length of the list?
11while i < len(scores):
12    # body of the loop (aka do some stuff)
13    # apply the transformation
14    proportion = scores[i]/100
15    # add the transformed value to the output list
16    proportions.append(proportion)
17    # update: increment i so the condition eventually becomes False
18    i += 1
19
20proportions
[0.65, 0.82, 0.23, 0.97, 1.0, 0.95]

Practice: Code Tracing with Indefinite Loops#

Predict the output of each code snippet before running the cell!

Trace 1#

1x = 10
2while x > 0:
3    print(x)
4    x = x - 3

What is the output?

  • A) 10 7 4 1

  • B) 10 7 4

  • C) 7 4 1

  • D) 10 7 4 1 -2

Answer:

A) 10 7 4 1

Trace the value of x at the start of each iteration:

  • x = 10: 10 > 0 is True, prints 10, x becomes 7

  • x = 7: 7 > 0 is True, prints 7, x becomes 4

  • x = 4: 4 > 0 is True, prints 4, x becomes 1

  • x = 1: 1 > 0 is True, prints 1, x becomes -2

  • x = -2: -2 > 0 is False, loop ends

The print happens before the subtraction, and -2 is never printed because the condition is checked at the top of each iteration.

Trace 2#

1count = 0
2n = 1
3while n < 100:
4    n = n * 2
5    count = count + 1
6print(n, count)

What is the output?

  • A) 64 6

  • B) 128 7

  • C) 100 7

  • D) 256 8

Answer:

B) 128 7

n doubles each iteration: 1 → 2 → 4 → 8 → 16 → 32 → 64 → 128. When n becomes 128, the condition 128 < 100 is False, so the loop ends. It took 7 doublings, so count is 7. Note that n ends at 128, not 64 — the doubling to 128 happens inside the loop before the condition is checked again.

Trace 3#

1items = [4, 7, 2, 9, 1]
2i = 0
3while i < len(items) and items[i] != 9:
4    i += 1
5print(i)

What is the output?

  • A) 9

  • B) 4

  • C) 3

  • D) 5

Answer:

C) 3

The loop increments i until it either reaches the end of the list or finds 9:

  • i = 0: items[0] is 4, not 9, so i becomes 1

  • i = 1: items[1] is 7, not 9, so i becomes 2

  • i = 2: items[2] is 2, not 9, so i becomes 3

  • i = 3: items[3] is 9, so items[i] != 9 is False, loop ends

i is 3, which is the index where 9 was found — not the value 9 itself.

Trace 4#

1nums = [3, 5, 2, 8, 6]
2i = 0
3total = 0
4while i < len(nums):
5    if nums[i] % 2 == 0:
6        total += nums[i]
7    i += 1
8print(total)

What is the output?

  • A) 24

  • B) 16

  • C) 10

  • D) 8

Answer:

B) 16

The loop goes through every item in the list (like a for loop would), but only adds even numbers to total:

  • 3: odd, skip

  • 5: odd, skip

  • 2: even, total = 0 + 2 = 2

  • 8: even, total = 2 + 8 = 10

  • 6: even, total = 10 + 6 = 16

Note that i += 1 is outside the if, so i always increments — otherwise we’d have an infinite loop!

Trace 5#

1words = ["cat", "dog", "bird", "fish"]
2result = []
3i = len(words) - 1
4while i >= 0:
5    result.append(words[i])
6    i -= 1
7print(result)

What is the output?

  • A) ["cat", "dog", "bird", "fish"]

  • B) ["fish", "bird", "dog", "cat"]

  • C) ["fish"]

  • D) ["bird", "dog", "cat"]

Answer:

B) ["fish", "bird", "dog", "cat"]

This loop walks through the list backwards by starting i at the last index (3) and decrementing:

  • i = 3: appends "fish", i becomes 2

  • i = 2: appends "bird", i becomes 1

  • i = 1: appends "dog", i becomes 0

  • i = 0: appends "cat", i becomes -1

  • i = -1: -1 >= 0 is False, loop ends

The result is the original list in reverse order.

Trace 6#

1values = [1, 3, 5, 7, 9, 11]
2i = 0
3while i < len(values):
4    i += 2
5print(i, len(values))

What is the output?

  • A) 4 6

  • B) 6 6

  • C) 5 6

  • D) 10 6

Answer:

B) 6 6

The loop increments i by 2 each time, but doesn’t do anything else with the list:

  • i = 0: 0 < 6 is True, i becomes 2

  • i = 2: 2 < 6 is True, i becomes 4

  • i = 4: 4 < 6 is True, i becomes 6

  • i = 6: 6 < 6 is False, loop ends

i is 6, which equals len(values). This is a common pattern — when a while i < len(...) loop ends normally, i equals the length of the list.

Practice: Writing Indefinite Loops#

Part 1: Flip the stopping rule#

Remember: problems usually tell you when to stop, but a while line needs to have a rule for when to keep going. So for each stopping rule below, write the while line. Then read it out loud as “keep going as long as…” to check yourself!

Flip 1#

Stop when: battery is 5 or lower.

Answer:

1while battery > 5:

The opposite of “5 or lower” is “above 5”. A common mistake is while battery >= 5:. That would keep going when battery is exactly 5, but 5 is supposed to stop us!

Flip 2#

Stop when: the user’s command is "quit".

Answer:

1while command != "quit":

The opposite of “is” (==) is “is not” (!=).

Flip 3#

Stop when: total is over 50 or num_items is 10 or more.

Answer:

1while total <= 50 and num_items < 10:

Each part gets flipped, and the or becomes an and. Any one reason is enough to stop. So to keep going, neither reason can be true yet.

Flip 4#

song_over and skipped are Boolean variables.

Stop when: song_over is True or skipped is True.

Answer:

1while not song_over and not skipped:

Since these are already Booleans, we flip them with not. No need to write song_over == False.

Flip 5#

We’re walking through a list called mascots, and i is our current index.

Stop when: we’ve run out of items in the list or the item at i is "Testudo".

Answer:

1while i < len(mascots) and mascots[i] != "Testudo":

Order matters here! Python checks the left side of the and first. If that’s False, it doesn’t bother checking the right side. So when i has run off the end of the list, i < len(mascots) is False, and mascots[i] never runs. If you swapped the two sides, you’d get an IndexError any time the list doesn’t contain "Testudo".

Part 2: Writing indefinite loops#

For each of these, before you write any code, I want you to say these out loud (or write them as comments):

  1. Initialize: what variables do I need to set up before the loop?

  2. Condition: what’s the keep-going rule?

  3. Update: what changes in the body that brings us closer to stopping?

Write your code in the cell, run it to check that it gives you what you expect, then compare with the answer. It’s ok if your code doesn’t look exactly like mine! If it gives the right output (and doesn’t run forever), you’re in good shape.

Write 1: Battery life#
1battery = 100
2# watching a video uses up 15 percent of the battery every hour
3# keep watching until the battery is below 20
4# then print how many hours you watched, and how much battery is left

Answer:

1battery = 100
2hours = 0
3
4while battery >= 20:
5    battery = battery - 15
6    hours += 1
7
8print(hours, battery)  # 6 10

The stopping rule is “below 20”, so the keep-going rule is “20 or above”. Notice that the battery ends at 10, below 20. That’s because it was at 25 at the top of the last iteration, which was enough to keep going. Then it dropped by 15.

Write 2: How long until my savings double?#

Finish this function. It should return how many years it takes for balance to reach at least double its starting amount, when it grows by rate each year. (To grow a balance by a rate of 0.05, multiply it by 1.05, or in general, by 1 + rate.)

1def years_to_double(balance, rate):
2    years = 0
3    # your code here
4
5    return years
6
7print(years_to_double(1000, 0.05))  # should print 15
8print(years_to_double(500, 0.10))   # should print 8

Answer:

1def years_to_double(balance, rate):
2    years = 0
3    goal = balance * 2
4    while balance < goal:
5        balance = balance * (1 + rate)
6        years += 1
7    return years

We need the separate goal variable. If you wrote while balance < balance * 2:, the goal would move every time the balance grows, and the loop would never end!

Write 3: Rewrite a definite loop#

Rewrite this for loop as a while loop. It should produce the same result.

1prices = [12, 45, 8, 30, 5]
2cheap = []
3for price in prices:
4    if price < 20:
5        cheap.append(price)
6print(cheap)
1prices = [12, 45, 8, 30, 5]
2cheap = []
3# your code here

Answer:

 1prices = [12, 45, 8, 30, 5]
 2cheap = []
 3
 4i = 0
 5while i < len(prices):
 6    if prices[i] < 20:
 7        cheap.append(prices[i])
 8    i += 1
 9
10print(cheap)  # [12, 8, 5]

The for loop was doing three jobs for us that we now have to do ourselves: starting at the first item (i = 0), knowing when to stop (i < len(prices)), and moving to the next item (i += 1). Be careful to line up i += 1 with the if (so it’s outside of it!). We want to move on whether or not the price was cheap.

Write 4: Making a playlist#
1songs = [4, 3, 5, 2, 4, 6, 3]  # length of each song, in minutes
2commute = 20
3# add songs to your playlist in order,
4# until the playlist is at least as long as your commute, or you run out of songs
5# then print how many songs you used, and the total minutes

Once it works, change commute to 60 and make sure that your code still works (it should use all 7 songs, for 27 minutes).

Answer:

 1songs = [4, 3, 5, 2, 4, 6, 3]
 2commute = 20
 3
 4total = 0
 5i = 0
 6while total < commute and i < len(songs):
 7    total += songs[i]
 8    i += 1
 9
10print(i, total)  # 6 24

We flip the stopping rule (at least as long as the commute or out of songs) into a keep-going rule (shorter than the commute and still have songs). When the loop ends, i tells us how many songs we used, since we add 1 to it for each song.

Write 5: First failing score#
1scores = [88, 92, 75, 58, 90, 43]
2# find the index of the first score below 60, and stop looking once you find it
3# print "First failing score is at index" and the index
4# if there are no scores below 60, print "Everyone passed" instead

Once it works, test it with scores = [88, 92, 75].

Answer:

 1scores = [88, 92, 75, 58, 90, 43]
 2
 3i = 0
 4while i < len(scores) and scores[i] >= 60:
 5    i += 1
 6
 7if i < len(scores):
 8    print("First failing score is at index", i)  # 3
 9else:
10    print("Everyone passed")

The body of this loop is just one line, because the condition is doing all of the checking. The loop could have stopped for two reasons, so the if afterward figures out which one it was. If i is still a valid index, we stopped because we found a failing score. Don’t check scores[i] < 60 after the loop. If everyone passed, i is past the end of the list, and you’d get an IndexError.

Write 6: Login attempts#
1attempts = ["password1", "terps2026", "fearTheTurtle", "letmein"]  # what the user typed, in order
2correct = "fearTheTurtle"
3max_tries = 3
4# go through the attempts until one of them is correct,
5# or the user has used up max_tries, or there are no more attempts
6# then print "Access granted" if they got it right, and "Locked out" if they didn't

Once it works, change correct to "letmein". The user should get locked out, since that attempt comes after their 3 tries are used up.

Answer:

 1attempts = ["password1", "terps2026", "fearTheTurtle", "letmein"]
 2correct = "fearTheTurtle"
 3max_tries = 3
 4
 5i = 0
 6found = False
 7while not found and i < max_tries and i < len(attempts):
 8    if attempts[i] == correct:
 9        found = True
10    i += 1
11
12if found:
13    print("Access granted")
14else:
15    print("Locked out")

Three stopping rules, so three parts joined by and. The found variable works just like the one in the guessing game. It also makes the check after the loop easy, since it remembers whether we got a correct attempt.

Write 7: Running tab#

This one uses input(), so it needs to be run interactively (e.g., copy-paste into a Python terminal).

Write a program that asks the user for the price of an item (in whole dollars), and keeps asking until the user types done. Then print the total.

Answer:

1total = 0
2
3user_input = input("Price of the item (or done to stop): ")
4
5while user_input != "done":
6    total += int(user_input)
7    user_input = input("Price of the item (or done to stop): ")
8
9print("Your total is", total)

We have to ask twice: once before the loop (so the condition has something to check the first time), and again at the end of the body. That second input() is our update. Without it, user_input never changes and the loop runs forever. Also notice that we only call int() inside the loop, after we’ve checked that the input isn’t done.

Breaking a loop with the break statement#

The break statement ends the current loop immediately and jumps to the statement right after the loop. It’s like an emergency exit that can happen anywhere in the body of the loop.

Remember that the while condition is a keep-going rule, and it’s only checked at the top of the loop. break is the opposite: you use it to write a stopping rule directly, at the exact point in the body where you find out it’s time to stop (e.g., right after reading the user’s input, or right after finding the thing you were looking for).

Here’s an example: search for “John” in a list, and stop as soon as we find him (no need to keep checking the rest).

 1found = False # default is we haven't found it
 2names = ["Joel", "John", "Jane", "Jamie", "Lisa", "Anna", "Fred"]
 3for name in names:
 4    print(name)
 5    if name == "John":
 6        found = True
 7        print("Found!")
 8        break
 9print("We're done with the loop")
10if found:
11    print("Found john!")
12else:
13    print("Didn't find john")
Joel
John
Found!
We're done with the loop
Found john!

Notice that the loop only printed “Joel” and “John” — it didn’t continue through the rest of the list because break exited the loop early.

A common pattern with break is while True: a loop that runs forever unless a break is reached. This is handy for user interfaces where you don’t know when the user will want to stop. This code uses input(), so it needs to be run interactively (e.g., copy-paste into a Python terminal):

1while True:
2    line = input('> ')
3    if line == 'done':
4        break
5    print(line)
6print('Done!')

Worked example: four ways to stop a loop#

Let’s put all of this together with one problem, and solve it four different ways. Each way fixes something awkward about the one before it.

The problem: Write a program for a fundraiser. Use the input() function to repeatedly prompt the user for a donation, and keep asking until the user says “time’s up”, or the amount reaches or exceeds a fundraising goal.

All of these use input(), so they need to be run interactively (e.g., copy-paste into a Python terminal).

Version 1: put everything in the while condition#

Let’s start with the most literal translation of the problem. The problem gives us a stopping (“until”) rule: stop when the user says “time’s up” or we reach the goal. But a while loop decides whether to keep looping with a keep-going (“as long as”) rule. So we flip the rule into a keep-going rule: keep going as long as the user hasn’t said “time’s up” and we haven’t reached the goal.

 1current_amount = 0
 2fundraising_goal = 2500
 3
 4# get the first input BEFORE the loop, so the while condition has something to check
 5user_input = input("How much do you want to donate (or say time's up to stop):\n")
 6
 7# keep going as long as the user hasn't said time's up AND we haven't reached the goal
 8while user_input != "time's up" and current_amount < fundraising_goal:
 9
10    # we do our donation handling
11    new_donation = int(user_input)
12    current_amount += new_donation
13    print("Thanks! New total is", current_amount)
14
15    # and only ask again if we still need more money
16    if current_amount < fundraising_goal:
17        user_input = input("How much do you want to donate (or say time's up to stop):\n")
18
19print("Our total raised is", current_amount)
20print("Thank you for playing!")

This works! But notice a couple of awkward things:

  • We have to write the input() line twice: once before the loop (so the while condition has something to check the first time), and once at the end of the body.

  • We need an extra if at the end of the body. Otherwise, after we reach the goal, we’d ask the user for one more donation that we just throw away.

These both happen because the while condition only gets checked at the top of the loop. But we find out whether to stop in the middle of the loop: right after we read the input, and right after we add the donation.

Version 2: use a flag variable#

What if we could say “time to stop” at the exact point in the loop where we find out? One way to do this is with a flag: a Boolean variable that starts as True, and that we set to False whenever we hit one of our stopping rules. Then the while condition just checks the flag. (This is the same idea as the found variable in the guessing game.)

 1current_amount = 0
 2fundraising_goal = 2500
 3
 4# flag: start out assuming we want to keep going
 5keep_going = True
 6
 7while keep_going:
 8
 9    # get input (now we only need to write this once!)
10    user_input = input("How much do you want to donate (or say time's up to stop):\n")
11
12    # stopping rule 1: user says time's up
13    if user_input == "time's up":
14        print("Ok, out of time! Stopping.")
15        # set the flag to False
16        # so that when we go back to the while statement, we'll stop
17        keep_going = False
18    else:
19        # we do our donation handling
20        new_donation = int(user_input)
21        current_amount += new_donation
22        print("Thanks! New total is", current_amount)
23
24        # stopping rule 2: we've met our goal
25        if current_amount >= fundraising_goal:
26            print("We've met our goal! Stopping.")
27            # set the flag to False
28            # so that when we go back to the while statement, we'll stop
29            keep_going = False
30        else:
31            print("Amount left to raise to reach our goal:", fundraising_goal - current_amount)
32
33print("Our total raised is", current_amount)
34print("Thank you for playing!")

This is nicer: we only ask for input in one place, and each stopping rule sits right where we find out about it.

But notice that we still need elses. Why? Setting keep_going = False doesn’t stop the loop right away! The rest of the body still runs, and the loop only stops when it gets back to the top and checks the condition again. So if the user says “time’s up”, we need the else to skip the int(user_input) line (which would crash, since “time’s up” isn’t a number!).

So really, we want a way to say “stop now.”

Version 3: use break#

That’s exactly what break does. Take Version 2, and:

  • replace keep_going = False with break

  • replace while keep_going: with while True: (since nothing changes the flag anymore, it’s always True!)

  • remove the elses, since break already skips the rest of the body

 1current_amount = 0
 2fundraising_goal = 2500
 3
 4# this just keeps looping :)
 5# which is ok, since we have opportunities to break the loop
 6# in the body of the loop!
 7while True:
 8
 9    # get input
10    user_input = input("How much do you want to donate (or say time's up to stop):\n")
11
12    # exit path 1
13    if user_input == "time's up":
14        print("Ok, out of time! Stopping.")
15        break
16
17    # we do our donation handling
18    new_donation = int(user_input)
19    current_amount += new_donation
20    print("Thanks! New total is", current_amount)
21
22    # exit path 2: meeting our fundraising goal
23    if current_amount >= fundraising_goal:
24        print("We've met our goal! Stopping.")
25        break
26
27    # if we get here, we haven't hit the goal yet
28    print("Amount left to raise to reach our goal:", fundraising_goal - current_amount)
29
30print("Our total raised is", current_amount)
31print("Thank you for playing!")

Now the body reads straight down, top to bottom: get input, check exit path 1, do the main work, check exit path 2, and otherwise go around again. Each break sits right after the line that tells us whether to stop.

NOTE: while True isn’t magic! It’s basically a flag that never changes, so the only way out of the loop is a break. This also means that if you write while True, you need to make sure that a break will eventually happen, or your loop will run forever!

Version 4: mix and match#

You don’t have to pick just one approach. Look at our two stopping rules again:

  • “we’ve reached the goal”: we can check this at the top of the loop, before we ask for input. So it can go in the while condition.

  • “the user says time’s up”: we can only check this after we read the input, in the middle of the body. So it’s a good fit for break.

 1current_amount = 0
 2fundraising_goal = 2500
 3
 4# keep going as long as we haven't reached the goal
 5while current_amount < fundraising_goal:
 6
 7    # get input
 8    user_input = input("How much do you want to donate (or say time's up to stop):\n")
 9
10    # early exit path
11    # we only find out the user wants to stop AFTER reading the input
12    if user_input == "time's up":
13        print("Ok, out of time! Stopping.")
14        break
15
16    # we do our donation handling
17    # if we don't exit early
18    new_donation = int(user_input)
19    current_amount += new_donation
20    print("Thanks! New total is", current_amount)
21
22print("Our total raised is", current_amount)
23print("Thank you for playing!")

So which one should I use?#

All four versions do the same thing. The difference is where the stopping rules live:

Version

“Reached the goal” rule

“Time’s up” rule

1: while condition

while condition

while condition

2: flag

sets flag, checked by while condition

sets flag, checked by while condition

3: break

break

break

4: mix

while condition

break

A good rule of thumb: for each stopping rule, ask yourself at what point in the loop do I have the information I need to check it?

  • If you can check it at the top of the loop, before doing any of the work, flip it into a keep-going rule and put it in the while condition. The loop will stop when that condition becomes False.

  • If you only find out in the middle of the body (e.g., right after reading input, or right after finding what you’re looking for), check it right there and use break to stop immediately.

PRACTICE: Rewrite the guessing game from earlier in this chapter using while True and break. Which version do you find easier to read?

Answer:

 1number = 5
 2
 3while True:
 4    guess = input("Try to guess the number between 1 and 10, or say `exit` to quit")
 5
 6    # exit path 1
 7    if guess == "exit":
 8        break
 9
10    # exit path 2
11    if int(guess) == number:
12        print("You got it!")
13        break
14
15print("Thanks for playing!")

I think this version is easier to read. We only need to write input() once now, and we don’t need the found variable, since each break sits right where we find out that it’s time to stop.

Practice: Choosing how to loop and where to stop#

Part 1: for or while?#

For each scenario, pick the best answer. Pay attention to the reason as well as the loop!

Choose 1#

Ask the user for exactly 5 movie ratings, then print the average.

  • A) while, because the program has to wait for the user to type something

  • B) for, because you know before the loop starts that it needs to run 5 times

  • C) for, because a loop that adds up numbers has to be a for loop

  • D) while, because the user could type any number

Answer:

B) Do you know how many iterations you need before the loop starts? Here you do. If you picked A, notice that input() can go inside any kind of loop, so using it doesn’t make this a while problem. If you picked C, you’ve got the right loop but the wrong reason: the counting pattern can be written with either kind of loop.

Choose 2#

Keep asking the user for a username until they type one that isn’t already in the list taken_names.

  • A) for, because taken_names is a list, and for loops go through lists

  • B) while, because the code needs to use input()

  • C) for, because range(100) would give the user plenty of tries

  • D) while, because you can’t know how many tries it will take until the user actually types an available name

Answer:

D) The number of iterations depends on what happens during the loop, which is exactly when you want while. If you picked B, you’ve got the right loop but the wrong reason (Choose 1 used input() too, and that one was a for loop!). If you picked A, notice that we aren’t going through taken_names item by item. We’re repeating a question, and we only use the list to check each answer.

Choose 3#

Convert each temperature in a list from Fahrenheit to Celsius.

  • A) while, because you don’t know how long the list will be when you write the code

  • B) for, because while loops can’t go through a list

  • C) for, because you want to visit each item exactly once, and the list’s length is known when the loop starts

  • D) while, because the temperatures need to be changed

Answer:

C) It doesn’t matter if you know how long the list is while you’re writing the code! The loop’s job is “do this once for each item”, and Python knows how many items there are when the loop starts. That’s why A doesn’t hold up. If you picked B, you’ve got the right loop but the wrong reason: we saw earlier in this chapter that any for loop can be written as a while loop.

Choose 4#

Go through a list of orders, and stop at the first order that is over $100.

  • A) Either one works: while with the stopping rule flipped into the condition, or for with a break

  • B) for, and only for, because we’re going through a list

  • C) for is the best fit, because you know exactly how many orders you’ll need to check

  • D) while, and only while, because a for loop always goes through all of the items

Answer:

A) We don’t know how many orders we’ll check (so C’s reason is wrong). But we do have a list to go through, so both kinds of loop can work. D would be true if we didn’t have break! You’ll get to write it both ways in Break 3 below.

Part 2: Stopping rules with break#

Remember our rule of thumb: for each stopping rule, ask at what point in the loop do I have the information I need to check it?

Break 1 and Break 2 use input(), so they need to be run interactively (e.g., copy-paste into a Python terminal).

Break 1: Running tab, take 2#

Rewrite your program from Write 7 (the running tab) using while True and break, so that you only need to write input() once.

Answer:

 1total = 0
 2
 3while True:
 4    user_input = input("Price of the item (or done to stop): ")
 5
 6    if user_input == "done":
 7        break
 8
 9    total += int(user_input)
10
11print("Your total is", total)

The break comes right after the input(), because that’s the moment we find out whether to stop. It also comes before int(user_input), which would crash if it tried to convert "done" to a number.

Break 2: Shopping list#

Write a program that asks the user for items to add to a shopping list, one at a time. Stop when the user types done, or when the list has 5 items. Then print the list.

Before you write any code, decide: should each stopping rule go in the while condition, or should it be a break?

Answer:

 1items = []
 2
 3while len(items) < 5:
 4    item = input("Add an item (or done to stop): ")
 5
 6    if item == "done":
 7        break
 8
 9    items.append(item)
10
11print(items)

We can check the length of the list at the top of the loop, before asking for anything, so that rule goes in the while condition. But we only find out if the user typed done after we’ve asked them (in the middle of the body), so that rule is a good fit for break. This is the same mix as Version 4 of the fundraiser.

Break 3: One problem, two loops#

Print each order, in order, until you reach the first order over 100. Don’t print that order or anything after it, so this list should print 20 and then 45. Solve it twice: once with for and break, and once with while and no break.

1orders = [20, 45, 130, 15, 210]
2# version 1: for and break
1orders = [20, 45, 130, 15, 210]
2# version 2: while, no break

Answer:

1# version 1: for and break
2for order in orders:
3    if order > 100:
4        break
5    print(order)
1# version 2: while, no break
2i = 0
3while i < len(orders) and orders[i] <= 100:
4    print(orders[i])
5    i += 1

In version 1 we write the stopping rule directly (order > 100). In version 2 we flip it into a keep-going rule (orders[i] <= 100) and take care of the index ourselves. The check also has to come before the print in version 1, or we’d print the 130.

Common errors#

Indentation is key!#

The way that Python knows what counts as the body of code for a loop (whether definite or indefinite) is through indentation.

You must indent all code that goes in the body underneath the for/while statement (after the colon).

If you fail to indent the first line of code in the body, you will get an IndentationError.

If you fail to indent anything after the first line of code in the body, you will be committing a semantic error: Python will not alert you because it is legal code. But your program will not do what you intend it to do.

1for i in range(5):
2print(i)
  Cell In[65], line 2
    print(i)
    ^
IndentationError: expected an indented block after 'for' statement on line 1
1# i want to step through a list of numbers, multiply each of them by 5 and print them out
2nums = [1,2,3,4,5]
3for num in nums:
4  new_num = num*5
5print(new_num)
25

Notice how this only prints 25 (the last value), not all five values! That’s because print(new_num) is not indented under the for, so Python treats it as code that runs once after the loop finishes, not during each iteration. To fix this, indent print(new_num) to match new_num = num*5.

IndexError when looping through a list#

This comes up mostly with while loops. So, while it’s possible to do any for loop with a while loop, you want to be careful with it.

 1names = ["Joel", "John", "Jane", "Jamie", "John"]
 2to_grab = [] # output list, initialize to empty list
 3
 4index = 0 # set initial index to zero
 5while index < 10: # BUG: 10 is larger than the list! should be len(names)
 6  print(index)
 7  name = names[index] # get the name at this index
 8  if name == "John": # check if is john / meets my criteria for being filtered
 9    to_grab.append(name) # add the item to the output list
10  index += 1 # increment the index
11
12# print out the result
13print(to_grab)
0
1
2
3
4
5
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[67], line 7
      3 
      4 index = 0 # set initial index to zero
      5 while index < 10: # BUG: 10 is larger than the list! should be len(names)
      6   print(index)
----> 7   name = names[index] # get the name at this index
      8   if name == "John": # check if is john / meets my criteria for being filtered
      9     to_grab.append(name) # add the item to the output list
     10   index += 1 # increment the index

IndexError: list index out of range
1# basic iteration through a list using indices
2names = ["Joel", "John", "Lane", "Jamie", "Freddy"]
3
4for index in range(6):
5  name = names[index]
6  print(index, name)
0 Joel
1 John
2 Lane
3 Jamie
4 Freddy
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[68], line 5
      1 # basic iteration through a list using indices
      2 names = ["Joel", "John", "Lane", "Jamie", "Freddy"]
      3 
      4 for index in range(6):
----> 5   name = names[index]
      6   print(index, name)

IndexError: list index out of range

Infinite loops#

Remember that with indefinite loops, the while condition must eventually become False, or the loop needs another way to exit (like break). Otherwise, it will go forever! A common error is to forget to include code in the body of the loop that changes something the condition depends on.

1n = 5
2while n > 0:
3    print(n)
4    n = n - 1
5print("Blast off!")
5
4
3
2
1
Blast off!

This works because n = n - 1 ensures the condition (n > 0) will eventually become False. What would happen if we forgot that line? The loop would run forever!

Here’s another example where the while loop condition can never become False because "John" isn’t in the list. The loop will keep going, incrementing index past the end of the list, and crash with an IndexError:

 1names = ["Joel", "Jane", "Jamie"]
 2to_grab = [] # output list, initialize to empty list
 3
 4index = 0 # set initial index to zero
 5while len(to_grab) == 0: # keep going until we find something
 6    print(index)
 7    name = names[index] # get the name at this index
 8    if name == "John": # check if is john / meets my criteria for being filtered
 9        to_grab.append(name) # add the item to the output list
10    index += 1 # increment the index
11
12# print out the result
13print(to_grab)
0
1
2
3
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[70], line 7
      3 
      4 index = 0 # set initial index to zero
      5 while len(to_grab) == 0: # keep going until we find something
      6     print(index)
----> 7     name = names[index] # get the name at this index
      8     if name == "John": # check if is john / meets my criteria for being filtered
      9         to_grab.append(name) # add the item to the output list
     10     index += 1 # increment the index

IndexError: list index out of range

Practice: Fix the loop#

Each of these loops has a bug. For each one, first figure out what ACTUALLY happens when it runs, then fix it.

I didn’t make these runnable cells, because some of them never stop! If you want to try them out, paste them into python tutor (it gives up after a while, so you won’t get stuck).

Fix 1#

This code is supposed to print the battery level each hour until the battery is dead.

1battery = 100
2while battery != 0:
3    print(battery)
4    battery = battery - 15
5print("Dead!")

Answer:

What happens: it’s an infinite loop. The battery goes 100, 85, … 25, 10, -5, -20, and so on. It jumps right over 0, so battery != 0 is always True.

Fix: use a condition that covers the whole range of values where we want to keep going.

1while battery > 0:

Be suspicious of != with numbers that change by more than 1 at a time!

Fix 2#

This code is supposed to drain the battery until it reaches 20 or lower, then print the hours and the battery level. It should print 6 10.

1battery = 100
2hours = 0
3while battery <= 20:
4    battery = battery - 15
5    hours += 1
6print(hours, battery)

Answer:

What happens: it prints 0 100. The body of the loop never runs, because 100 <= 20 is False the very first time we check it.

Fix: “20 or lower” is the stopping rule. The while line needs to have the keep-going rule.

1while battery > 20:

Fix 3#

This code is supposed to count the even numbers in a list.

1nums = [3, 8, 5, 12]
2i = 0
3evens = 0
4while i < len(nums):
5    if nums[i] % 2 == 0:
6        evens += 1
7        i += 1
8print(evens)

Answer:

What happens: it’s an infinite loop that doesn’t print anything. The first number, 3, is odd, so we skip the body of the if. That means i stays at 0, and we check the 3 again, forever.

Fix: move the update out of the if, so that we move on to the next number no matter what.

1while i < len(nums):
2    if nums[i] % 2 == 0:
3        evens += 1
4    i += 1

Fix 4#

This code is supposed to add songs until the playlist is at least as long as the commute, or we run out of songs. It should print 3 12.

1songs = [4, 3, 5]
2commute = 20
3total = 0
4i = 0
5while total < commute or i < len(songs):
6    total += songs[i]
7    i += 1
8print(i, total)

Answer:

What happens: it crashes with an IndexError. After the third song, i is 3 and total is 12. We’ve run out of songs, but total < commute is still True. And with an or, one True is enough to keep going. So we try to get songs[3], which doesn’t exist.

Fix: when you flip a stopping rule with an or, the keep-going rule needs to have an and.

1while total < commute and i < len(songs):