…
…
Python Programming Fundamentals · Lesson 13 / 40 · Algorithms and loops
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
At Corner Café, Ada wants two things: a checklist with every item for every table ("Table 1: tea", "Table 1: latte" ...) and a price grid to hang next to the till, showing the totals for 1, 2, and 3 items. What the two requests have in common is that the output has rows and columns. In this lesson you will write a loop inside a loop, for the places where a single loop is not enough.
The program you write by the end of the lesson will produce the till grid for three drinks priced at $5, $10, and $15:
OutputQty 1: 5 10 15
Qty 2: 10 20 30
Qty 3: 15 30 45In this lesson you will be able to:
Recall from earlier lessons: the line for name in sequence: runs the indented body once for each item of the sequence. range(1, 4) gives 1, 2, and 3; the stop value is not included. A string is walked through character by character, and a ready-made list written in square brackets is walked through item by item. The lines in the body are repeated in every iteration; an unindented line after the loop runs once.
So far you have walked through a single sequence: the tables or the items. Ada's checklist needs both together: every item for every table. If you write a loop for the tables, the items are missing; if you write one for the items, the tables are. The solution lies in this observation: any kind of code can go in the body of a loop, including another loop. When one loop sits inside another, it is called a nested loop. We will call the first the outer loop and the second the inner loop.
The whole rule is one sentence: in every iteration of the outer loop, the inner loop runs again from start to finish.
Example 1 (case): Table × item checklist
for table in range(1, 3): for item in ["tea", "latte"]: print(f"Table {table}: {item}")
OutputTable 1: tea
Table 1: latte
Table 2: tea
Table 2: latteLet's read this code step by step. The outer loop starts with table = 1 and enters its body. The body contains the inner loop; in this iteration the inner loop runs twice: first item = "tea", then item = "latte". Each time, print runs. When the items of the inner loop are used up, the body of the outer loop ends too, and the outer loop moves to its second iteration: table = 2. Now notice: the inner loop does not continue where it left off; it starts over, with "tea". In the end, four lines are printed. Look at the indentation: print is indented twice (8 spaces) because it is in the body of both the outer and the inner loop.
| Iteration | table | item | Printed |
|---|---|---|---|
| 1 | 1 | tea | Table 1: tea |
| 2 | 1 | latte | Table 1: latte |
| 3 | 2 | tea | Table 2: tea |
| 4 | 2 | latte | Table 2: latte |
This order is like the hour hand and the minute hand of a clock. The hour hand does not move to the next hour until the minute hand has made a full turn; and the minute hand starts again from 12 every hour.
Follow the code below step by step. At each step, look at the item box: when the outer loop moves to its second iteration, the item box does not stay at "B"; it becomes "A" again. The line that says "done" is unindented, so it runs once at the very end.
Run the code line by line: see which line runs next, the variable boxes and the output.
for table in range(1, 3): for item in "AB": print(table, item) print("done")
So how many times does the inner body run in total? The outer loop ran 2 iterations, and in each of them the inner loop ran 2 iterations: 2 × 2 = 4. The general rule: the inner body runs outer iterations × inner iterations times. The most common mistake is to add these numbers. Try it yourself.
How many times does print run in this code?
for i in range(3): for j in range(4): print(i, j)
Iteration counts are multiplied, not added. For 20 tables and 10 items, the checklist has 20 × 10 = 200 lines. This product grows fast: three levels of nested loops with 100 iterations each mean a million operations. For the small tables in this lesson that is not a problem; but when you work with large data, keep the cost of nested loops in mind. The number of iterations of the inner loop can change in each outer iteration; then, instead of multiplying, you add up the count of each iteration one by one. You will see this in section 3, and the last line below tests it. Now match each code to its iteration count.
How many times does the inner body run in total in each nested loop?
For each row, pick its match from the list, then check.
range(2) inside range(5)range(4) inside range(4)range(1, 4) inside "tea"range(3) inside range(0)for row in range(1, 4) inside range(row)The easiest way to think about a two-dimensional output is rows and columns. In the till grid, each quantity is a row and each price is a column. In a nested loop the job splits itself: the outer loop produces the rows, and the inner loop produces the columns of one row.
But there is a problem. Every time print is called, it moves to a new line. If you write print for each cell in the inner loop, every amount lands on its own line, and the grid turns into nine numbers stacked on top of each other. To keep the cells of a row side by side, you use the += update from lesson 2 together with the string joining from lesson 4: line += "..." adds to the end of the string. The pattern has three steps, and the place of each step is set by its indentation:
| Step | Line | Where it goes |
|---|---|---|
| Start | line = ... | At the beginning of the outer loop's body (4 spaces), before the inner loop |
| Grow | line += ... | In the inner loop's body (8 spaces) |
print(line) | In the outer loop's body (4 spaces), after the inner loop |
Every row must start with a brand-new, empty (or labeled) string; that is why the start goes inside the outer loop. The row must be printed once, when it has collected all its cells; that is why the print goes after the inner loop. To keep the cells aligned, you use the field width from lesson 4: f"{amount:>6}" right-aligns the number in a field of 6 characters.
Example 2 (case): The till price grid (the target program of the lesson)
# 1. One row for each quantity for quantity in range(1, 4): # 2. Start the row with the quantity line = f"Qty {quantity}:" # 3. Add a cell for each price for price in range(5, 16, 5): line += f"{quantity * price:>6}" # 4. Print the row when it is finished print(line)
OutputQty 1: 5 10 15
Qty 2: 10 20 30
Qty 3: 15 30 45The steps are named with comments; you will use the same four steps in the exercises. The code has three indentation levels. The leftmost level (0 spaces) is only the outer for line. The second level (4 spaces) runs once for each row: the start, the inner for line, and the print. The third level (8 spaces) runs once for each cell: line += .... range(5, 16, 5) starts at 5, goes up by 5, and stops before reaching 16: 5, 10, 15. In the first iteration, line starts as "Qty 1:", three cells are added, and then it is printed. In the second iteration, line becomes "Qty 2:" again; nothing is carried over from the previous row.
The same pattern can count cells, too. Ada wants to write the small, medium, and large sizes of latte and mocha on the menu, and she wonders how many combinations that makes. This time there is a counter that counts all the combinations; notice that it starts outside all the loops.
Example 3 (case): Size combinations and a counter
counter = 0 for drink in ["latte", "mocha"]: for size in "SML": print(f"{drink}-{size}") counter += 1 print(counter, "combinations")
Outputlatte-S
latte-M
latte-L
mocha-S
mocha-M
mocha-L
6 combinationsLook at the order of the output: first the three sizes of latte, then those of mocha. Whichever loop is on the outside, the output is grouped by its values. If you wanted to group by size (latte-S, mocha-S, latte-M ...), you would swap the places of the loops. The last line is unindented, so it runs once, at the end, and prints 2 × 3 = 6.
Now try the same pattern on Ada's terrace plan. The code below draws the tables laid out on the terrace with their row and number. Change the number of rows and columns; follow how many times each row runs and how the Total grows as a product.
Change the number of rows and columns on the terrace: how do the grid and the total change?
Pick a value; predict the output first, then look.
1row_count = 22column_count = 23total = 04for row in range(1, row_count + 1):5 line = ""6 for number in range(1, column_count + 1):7 line += f"[{row}-{number}]"8 total += 19 print(line)10print("Total", total, "tables")
[1-1][1-2] [2-1][2-2] Total 4 tables
Faded lines didn't run with this value. row_count sets the number of rows, and column_count sets the number of cells in each row. Because line = "" is at the start of the outer loop, every row starts empty; because print(line) is after the inner loop, every row is printed once. Because total starts outside all the loops, it counts all the tables: 2 × 3 = 6, 3 × 3 = 9.
Now change the till grid yourself. Example 2 is ready in the cell below. Do the following in order, and press Run at each step: (1) Add $20 as a fourth price; for this, it is enough to change only the stop value of range. (2) Extend the grid to 5 quantities. (3) Change :>6 to :>8: what changed? (4) Finally, move the print(line) line one indentation level (4 spaces) inward: why did the grid break, and how many lines were printed?
Try it now· not graded; doesn't affect progress
In the fourth step, print(line) went into the body of the inner loop and ran after every cell: the half-finished versions of every row were printed too, and the grid had 9 lines instead of 3. No error message appeared; Python assumes the indentation is what you meant. In the row × column pattern, the print goes after the inner loop.
So far the inner loop has run the same number of iterations in every outer iteration. But the number of iterations of the inner loop can be tied to the variable of the outer loop. If you write for col in range(row):, the inner loop runs once in the first row, twice in the second row, and three times in the third. This produces staircase patterns where each row is longer than the one before. The same idea is used in jobs like "pair each team with the teams after it" (see Example 8).
Example 4 (outside the case): Staircase pattern
for row in range(1, 4): line = "" for col in range(row): line += "#" print(line)
Output#
##
###When row is 1, range(1) gives one iteration and line becomes a single #. When row is 2, range(2) gives two iterations and line, because it started empty again, becomes ##. The inner body runs 1 + 2 + 3 = 6 times in total. The pattern is the same again: start, grow, print. Try putting these five lines in order yourself. Indentation is part of the right order: it tells you which line belongs to which loop.
Put the lines of the program that prints the staircase pattern (#, ##, ###) in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
A loop variable does not have to be a number. In a cinema hall, rows are named with letters and seats with numbers. The outer loop can walk through a string letter by letter, and the inner loop can walk through a range.
Example 5 (outside the case): Cinema seating plan
for seat_row in "ABC": line = "" for number in range(1, 5): line += f"[{seat_row}{number}]" print(line)
Output[A1][A2][A3][A4]
[B1][B2][B3][B4]
[C1][C2][C3][C4]Below, follow the first two rows of the plan step by step. Watch the line box: it is emptied at the start of each outer iteration, it grows one seat at a time in the inner loop, and it is printed when the inner loop ends.
Run the code line by line: see which line runs next, the variable boxes and the output.
for seat_row in "AB": line = "" for number in range(1, 4): line += f"[{seat_row}{number}]" print(line)
In nested loops, where a variable starts determines what it does. No error message appears; only the result changes. So for every variable, first ask: "What does this value hold: the whole grid, a single row, or a single cell?"
| Variable | Where it starts | Why |
|---|---|---|
A counter of all iterations, a grand total (total, counter) | Outside all the loops, at the top | It must not be reset in any iteration; it counts all the cells of all the rows |
The row text, the total of a row (line) | At the beginning of the outer loop's body | Every row must start fresh |
The value of a cell (quantity * price) | In the inner loop's body | It is recalculated for every cell |
One more detail: give the two loops different names. If you call both the outer and the inner loop variable item, the inner loop overwrites the value of the outer loop in every iteration. The outer loop still runs the right number of times, but inside the body you can no longer reach the table number:
for item in range(1, 3): for item in ["tea", "latte"]: print(item, item)
Outputtea tea
latte latte
tea tea
latte latteThe expected output was 1 tea, 1 latte ... The problem goes away when you give the outer variable its own name, like table. Now test the sneakiest line in the place table: this program wants to count all the table-item pairs.
What does this code print?
for table in range(1, 4): counter = 0 for item in ["tea", "latte"]: counter += 1 print(counter)
This is the result of the misconception that the place of a counter or a row text does not matter. The same line can be right for another job: if you want a total per table, you do the reset inside the outer loop (see Example 9). The right place depends on what the variable holds.
break ends only the nearest loopIn lesson 11 you saw that break ends the loop immediately. In a nested loop the question is: which loop? The answer: only the nearest loop it is inside. A break in the inner loop ends the inner loop; the outer loop continues from where it was, with its next iteration.
Ada takes the items to each table in order, but the latte machine is broken: when it is latte's turn, the serving at that table ends, and the waiter moves to the next table.
Example 6 (case): The broken latte machine
for table in range(1, 4): for item in ["tea", "latte", "water"]: if item == "latte": break print(table, item)
Output1 tea
2 tea
3 teaBefore running the code, think about this question: does break end the whole serving, or only that table?
What does the code in Example 6 print?
for table in range(1, 4): for item in ["tea", "latte", "water"]: if item == "latte": break print(table, item)
But what if you really need to leave both loops at once? Ada wants to find the first empty seat in the terrace plan; when she finds it, the search must stop completely. A single break is not enough: the inner loop ends, the outer loop moves to the next row and continues the search. The solution is the flag pattern from lesson 12: the flag starts as False, when the target is found in the inner loop the flag is raised and the inner loop is left with break; in the body of the outer loop, right after the inner loop, the flag is checked, and if it is raised, a second break ends the outer loop too.
Example 7 (case): The first empty seat
# 1. Taken seats and the flag taken = "A1 A2 A3 A4 B1" found = False # 2. Walk through the rows and the seats for seat_row in "ABC": for number in range(1, 5): seat = f"{seat_row}{number}" if seat not in taken: # 3. When found, raise the flag and leave the inner loop found = True break # 4. If the flag is raised, leave the outer loop too if found: break print("First empty seat:", seat)
OutputFirst empty seat: B2seat not in taken is the opposite of the in question from lesson 6: it gives True if the seat does not appear in the taken string. All four seats of row A are taken; B1 is taken; B2 is empty. The flag is raised, the inner break ends the inner loop, if found: in the outer body is true, and the second break stops the search completely. If you delete the two lines in step 4 and try it, the program prints First empty seat: C1: the inner loop ends at B2, but the outer loop moves to row C and stops again at C1. The flag is the way to tell the outer loop what happened in the inner loop.
The most common mistake in this lesson gives no error message at all. If you want to count all the table-item pairs and write the line counter = 0 inside the outer loop, the counter is reset at every table, and when the loops end it shows only the count of the last table. The program runs and prints a number; only the number is wrong. So after you write a nested loop, work out the result by hand with a small example: 3 tables × 2 items should make 6. If the program says 2, look at the place of the reset. The right way: start the variable that holds the total before all the loops.
The most effective way to understand nested loops is to fill in an iteration table by hand, as in Example 1. When you write down which value each variable takes in each iteration, it becomes clear why the program produces that output, and a variable that starts in the wrong place stands out by itself.
In a tournament with four teams, every team plays every other team once. Because the inner loop starts at home + 1, each pairing is printed once (1-2 is printed, 2-1 is not) and a team is not paired with itself. The inner loop is dependent: it runs 3, 2, 1, and 0 iterations; 6 matches in total.
team_count = 4 matches = 0 for home in range(1, team_count + 1): for away in range(home + 1, team_count + 1): print(f"Team {home} - Team {away}") matches += 1 print(matches, "matches")
OutputTeam 1 - Team 2
Team 1 - Team 3
Team 1 - Team 4
Team 2 - Team 3
Team 2 - Team 4
Team 3 - Team 4
6 matchesAda serves a tasting menu (latte $4.25, cookie $2.00, tea $1.25) to three tables; the tables have 2, 4, and 1 guests. Here two totals live together: table_total must start over at every table, so it is reset inside the outer loop; grand_total holds all the tables, so it starts at the very outside. Two rows of the place table in the same program.
grand_total = 0 for guests in [2, 4, 1]: table_total = 0 for price in [4.25, 2.00, 1.25]: table_total += guests * price print(f) grand_total += table_total (f)
Forgetting to indent the body of the inner loop. If you leave the line under the inner for line at the same level as the outer body (4 spaces), Python cannot find the body of the inner loop:
for table in range(1, 3): for item in "AB": print(table, item)
OutputIndentationError: expected an indented block after 'for' statement on line 2The message says, "I expected an indented block after the for on line 2." To fix it, pull the print line to 8 spaces: the lines of the inner body sit one level deeper than the inner for. Its sibling that gives no error message is more dangerous: if you accidentally pull a line like print(line), which should come after the inner loop, to 8 spaces, the program runs but prints after every cell. Resetting the counter inside the outer loop is another form of the same silent mistake.
+= in the inner loop, and is printed once after the inner loop; the counter that counts all iterations starts outside all the loops, and the two loops use different names.break ends only the nearest loop; to leave both loops at once, you raise a flag in the inner loop and check the flag in the outer loop.Next lesson: Unit 3 is done; next is the unit task, the Number guessing game, and after that you will write your own functions so you do not have to write the same job again and again.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputTable of 2: $15.00
Table of 4: $30.00
Table of 1: $7.50
Grand total: $52.50