Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 15

Nested Loops and the Loop else

This lesson goes with Episode 15 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

15.1 A loop inside a loop

The block of a loop can contain any statements. That includes another loop. A loop inside another loop is called a nested loop. The one on the outside is the outer loop; the one inside it is the inner loop.

for hour in range(1, 3):
    for minute in range(3):
        print(f"hour {hour}, minute {minute}")
    print("--- the hour is over ---")

Output

hour 1, minute 0
hour 1, minute 1
hour 1, minute 2
--- the hour is over ---
hour 2, minute 0
hour 2, minute 1
hour 2, minute 2
--- the hour is over ---

The whole inner loop is one of the statements in the outer loop's block. So for each value of hour, the inner loop starts from the beginning and runs all the way through.

Tracing it

Step hour minute What happens
1 1 — outer loop takes its first value
2 1 0 inner loop starts; prints
3 1 1 prints
4 1 2 prints; the inner loop is finished
5 1 2 prints the "over" line
6 2 — outer loop takes its next value
7 2 0 inner loop starts again from 0; prints
8 2 1 prints
9 2 2 prints; the inner loop is finished
10 2 2 prints the "over" line; the outer loop is finished

The important rows are 2 and 7. Every time the outer loop begins a new pass, the inner loop is started afresh. The inner variable changes quickly, like the minute hand. The outer variable changes slowly, like the hour hand.

Indentation shows who owns what

for hour in range(1, 3):                       ◄── outer loop
    for minute in range(3):                    ◄── inner loop
        print(f"hour {hour}, minute {minute}") ◄── INNER block: runs 2 x 3 = 6 times
    print("--- the hour is over ---")          ◄── OUTER block only: runs 2 times
print("done")                                  ◄── after both loops: runs once
Indentation Belongs to Runs
8 spaces the inner loop once for every combination
4 spaces the outer loop only once per outer pass
0 spaces neither once, afterwards

Moving a line in or out by one level changes how many times it runs. In nested loops, the indentation rule from Chapter 11 matters more than ever.

The passes multiply

The outer loop makes 2 passes. For each one, the inner loop makes 3. The innermost line runs 2 × 3 = 6 times. In general:

Inner passes in total = (outer passes) × (inner passes per outer pass).

A 10-by-10 nested loop runs its inner block 100 times. A 1000-by-1000 one runs it a million times. Section 15.9 comes back to why that matters.

Quick check

How many times is print called here? for x in range(4): then (inner) for y in range(5): then (innermost) print(x, y). What is the first line printed, and the last?

Show the answer

Answer: 20 times (4 × 5). The first line is 0 0 and the last is 3 4.

Practice 15.1

Multiple choice

What does this program print?

count = 0
for x in range(3):
    for y in range(4):
        count += 1
print(count)
Choose one answer

Predict the output

What does it print? Look at the indentation of the print line.

total = 0
for x in range(1, 3):
    for y in range(3):
        total += x
    print(total)

Put the lines in order

Put the lines in order. The indentation of each line is fixed and shows which loop it belongs to.

The program in the right order prints:

Target

day 1 lesson 1
day 1 lesson 2
day over
day 2 lesson 1
day 2 lesson 2
day over
done
  1. print("done")
  2. print("day", day, "lesson", lesson)
  3. for lesson in range(1, 3):
  4. for day in range(1, 3):
  5. print("day over")

15.2 Staying on the same line

Nested loops are often used to print grids, and that needs control over where each line ends. You met end= briefly in Chapter 13. Here is what you need for this chapter. (The full story of print is in → Chapter 16.)

  • print(x) shows x and then moves to a new line.
  • print(x, end="") shows x and stays on the same line, adding nothing.
  • print(x, end=" ") shows x followed by a space, and stays on the line.
  • print() with nothing in the brackets just ends the current line.
print("A", end="")
print("B", end="")
print("C")
print("D")

Output

ABC
D

Practice 15.2

Predict the output

What does it print?

print("up", end="")
print("on", end=" ")
print("the")
print("hill", end="!")
print()

Fill in the blank

Fill in the blank so that all four numbers land on one line with nothing between them.

for n in range(1, 5):
    print(n, )
print()

The finished program prints:

Target

1234

15.3 Rows and columns

Here is the idea that makes every pattern problem easy:

The outer loop makes the rows. The inner loop makes the columns within one row. After the inner loop, end the line.

A rectangle of stars, 3 rows by 5 columns:

for row in range(3):
    for column in range(5):
        print("*", end="")
    print()

Output

*****
*****
*****

Read it as three steps that repeat: (1) the inner loop prints five stars side by side; (2) the bare print() ends that line; (3) the outer loop moves on to the next row.

The print() is in the outer block (four spaces). Indent it into the inner block, and every star lands on its own line. Leave it out, and all fifteen stars run together on one line. This single line is the most common thing to get wrong.

Showing the coordinates

Print the two loop variables in place of the star and you can see exactly how they move:

for row in range(3):
    for column in range(4):
        print(f"({row},{column})", end=" ")
    print()

Output

(0,0) (0,1) (0,2) (0,3)
(1,0) (1,1) (1,2) (1,3)
(2,0) (2,1) (2,2) (2,3)

Along each line, row stays fixed and column counts up. This picture, a grid of (row, column) positions, is the one to keep in your head for every nested loop.

A multiplication grid

A table has rows and columns, so it is a nested loop. rjust from Chapter 9 pads each number to the same width so the columns line up:

for row in range(1, 6):
    for column in range(1, 6):
        print(str(row * column).rjust(4), end="")
    print()

Output

   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

Each cell is row * column. The inner block uses both loop variables, which is what makes a nested loop more than "the same thing several times".

Practice 15.3

Fix the bug

This should print 2 rows of 6 # characters. It prints all 12 on one long line. Fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

######
######

Write code

Seat labels. Ask for the number of rows, then for the number of seats in each row. Print one line for each row. On a line, show every seat as the row number, a dash and the seat number, such as 2-3, with one space between seats. Rows and seats are counted from 1.

A space at the end of a line does not matter.

With the replies 2 then 3, the program prints the lines below. Your program must print exactly these lines.

Example run

1-1 1-2 1-3
2-1 2-2 2-3

Multiple choice

In the star rectangle of this section, the bare print() is moved one level deeper, into the inner block. What do you see?

Choose one answer

15.4 When the inner loop depends on the outer loop

In a rectangle, every row has the same length. For other shapes, the length of each row depends on which row it is. That means the inner loop's range uses the outer loop's variable.

A triangle

for row in range(1, 6):
    for column in range(row):
        print("*", end="")
    print()

Output

*
**
***
****
*****

range(row) is the whole trick. In row 1 the inner loop runs once, in row 2 twice, and so on.

A method for any pattern

Do not guess at loops. Make a small table of what each row needs, find the formula, and only then write the code.

For an upside-down triangle, 5 rows:

Row number Stars wanted Formula (rows = 5)
1 5 rows - row + 1
2 4
3 3
4 2
5 1
rows = 5
for row in range(1, rows + 1):
    for column in range(rows - row + 1):
        print("*", end="")
    print()

Output

*****
****
***
**
*

For a pyramid, each row needs some spaces first, then some stars. Two things per row means two inner loops, one after the other:

Row Spaces Stars
1 3 1
2 2 3
3 1 5
4 0 7
Formula rows - row 2 * row - 1
rows = 4
for row in range(1, rows + 1):
    for space in range(rows - row):
        print(" ", end="")
    for star in range(2 * row - 1):
        print("*", end="")
    print()

Output

   *
  ***
 *****
*******

The two inner loops are siblings: both sit inside the outer loop, at the same level, and run one after the other for each row.

A number triangle uses the inner variable as the thing to print:

for row in range(1, 5):
    for number in range(1, row + 1):
        print(number, end=" ")
    print()

Output

1
1 2
1 2 3
1 2 3 4

Quick check

What does the inner range need to be so that row 1 prints 2 stars, row 2 prints 4 and row 3 prints 6?

Show the answer

Answer: range(2 * row), with the outer loop as for row in range(1, 4).

Practice 15.4

Fill in the blank

Fill in the blank so that the first row has 4 stars and every later row has one star less.

rows = 4
for row in range(1, rows + 1):
    for column in range():
        print("*", end="")
    print()

The finished program prints:

Target

****
***
**
*

Predict the output

What does it print?

for row in range(1, 4):
    for number in range(row, 0, -1):
        print(number, end="")
    print()

Write code

Stairs on the right. Ask for a size. Print a triangle of * with that many rows, pushed to the right: row 1 has one star, row 2 has two stars, and so on, and every row is filled with spaces on the left so that all rows end in the same column. For size 3, the rows hold 2 spaces and 1 star, then 1 space and 2 stars, then 3 stars. Use nested loops.

With the reply 4, the program prints the lines below. Your program must print exactly these lines.

Example run

   *
  **
 ***
****

Put the lines in order

Put the lines in order so that the program prints the target. The indentation of each line is fixed.

The program in the right order prints:

Target

  #
 ##
###
  1. print()
  2. for space in range(3 - row):
  3. for row in range(1, 4):
  4. for star in range(row):
  5. print("#", end="")
  6. print(" ", end="")

15.5 Every pair

Many problems are about pairs: every combination of a shirt with a pair of trousers, every pair of players who must meet, every pair of numbers that add up to a target.

All combinations of two different lists

When the two things come from different collections, a plain nested loop gives every combination:

for size in ["small", "large"]:
    for drink in ["tea", "coffee", "juice"]:
        print(size, drink)

Output

small tea
small coffee
small juice
large tea
large coffee
large juice

Two sizes times three drinks: six combinations. (The values in square brackets are lists, which a for loop walks through item by item → Chapter 25.)

Pairs from one group

Now suppose four players must each play every other player once. A plain nested loop over the same group gives too much:

players = "ABCD"
for first in players:
    for second in players:
        print(first + second, end=" ")
    print()

Output

AA AB AC AD
BA BB BC BD
CA CB CC CD
DA DB DC DD

Sixteen pairs. But a player cannot play themselves (AA), and AB is the same match as BA. We want only the pairs above the diagonal of that grid.

The fix is to loop over positions, and to start the inner loop one place after the outer loop's position:

players = "ABCD"
matches = 0
for i in range(len(players)):
    for j in range(i + 1, len(players)):
        print(players[i] + players[j], end=" ")
        matches += 1
print()
print("Matches:", matches)

Output

AB AC AD BC BD CD
Matches: 6

range(i + 1, len(players)) means "only the players that come after player i". Each pair appears exactly once, and nobody is paired with themselves.

Inner loop starts at You get Count for 4 items
0 every ordered pair, including with itself 16
i each pair once, including with itself 10
i + 1 each pair of different items, once 6

The pattern for i in range(n) with for j in range(i + 1, n) is one to memorise. It appears whenever you compare items of a collection with each other: finding duplicates, finding the closest two values, checking for clashes in a timetable.

Searching for a combination

Which pairs of whole numbers from 1 to 10 multiply to give 24?

for x in range(1, 11):
    for y in range(x, 11):
        if x * y == 24:
            print(x, "x", y)

Output

3 x 8
4 x 6

Starting the inner loop at x avoids listing both 3 x 8 and 8 x 3. Trying every combination like this is called a brute-force search. It is not clever, but it is simple and it is correct, and for small ranges it is instant.

Practice 15.5

Fill in the blank

Fill in the blank so that each pair of different letters is printed once.

letters = "xyz"
for i in range(len(letters)):
    for j in range(, len(letters)):
        print(letters[i] + letters[j], end=" ")
print()

The finished program prints:

Target

xy xz yz

Write code

Pairs with a sum. Ask for a target number. Find every pair of whole numbers x and y from 1 to 9 with x smaller than y and x + y equal to the target. Print each pair on its own line in the form 1 + 9, with the smallest x first. Then print a last line: Pairs:, a space and the number of pairs found.

With the reply 10, the program prints the lines below. Your program must print exactly these lines.

Example run

1 + 9
2 + 8
3 + 7
4 + 6
Pairs: 4

Fix the bug

This should print each pair of numbers from 1 to 10 that multiply to give 18, once, with the smaller number first. It prints every pair in both orders. Fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

2 x 9
3 x 6

15.6 break in a nested loop

Here is a rule that surprises people:

break and continue only affect the loop they are directly inside: the innermost one.

for row in range(1, 4):
    for column in range(1, 6):
        if column == 3:
            break
        print(f"({row},{column})", end=" ")
    print("| row", row, "ended")

Output

(1,1) (1,2) | row 1 ended
(2,1) (2,2) | row 2 ended
(3,1) (3,2) | row 3 ended

When column reaches 3, break ends the inner loop. The outer loop knows nothing about it. It prints its "ended" line and carries on with the next row, where the inner loop starts again and breaks again.

That is often exactly what you want. But sometimes you want to stop everything as soon as you have found an answer. Suppose you are searching a grid for the first pair whose product is 12:

for x in range(1, 6):
    for y in range(1, 6):
        if x * y == 12:
            print("Found:", x, y)
            break

Output

Found: 3 4
Found: 4 3

It found two, because break only left the inner loop each time. There are three standard ways to leave both loops.

Way 1: a flag

Use a Boolean to carry the news from the inner loop out to the outer one:

found = False
for x in range(1, 6):
    for y in range(1, 6):
        if x * y == 12:
            print("Found:", x, y)
            found = True
            break
    if found:
        break

Output

Found: 3 4

The inner break leaves the inner loop. Straight afterwards, the outer block checks the flag and breaks as well. It is a little wordy, but anyone can read it.

Way 2: put the loops in a function

Inside a function, the return statement ends the whole function at once, however deeply nested the loops are. This is usually the cleanest solution, and you will be able to use it after → Chapter 19.

Way 3: the loop's else

Python loops have a feature made for this situation. It needs a section of its own.

Practice 15.6

Predict the output

What does it print?

for row in range(1, 4):
    for column in range(1, 5):
        if column > row:
            break
        print(column, end="")
    print(" end")

Multiple choice

What does this program print?

lines = 0
for x in range(3):
    for y in range(5):
        if y == 1:
            break
        lines += 1
    lines += 10
print(lines)
Choose one answer

15.7 The else of a loop

A for or while loop can be followed by an else block. It has nothing to do with the else of an if, and its name is widely agreed to be confusing. Here is what it means:

A loop's else block runs when the loop finishes normally. It is skipped if the loop was ended by break.

Many Python programmers read it in their heads as "no break".

for n in range(3):
    print(n)
else:
    print("The loop finished without a break.")

Output

0
1
2
The loop finished without a break.
for n in range(3):
    print(n)
    if n == 1:
        break
else:
    print("The loop finished without a break.")
print("After the loop")

Output

0
1
After the loop
   for item in sequence:
       if found_it:
           break  ───────────────┐   leaving by break skips the else
   else:                         │
       (runs only if the loop    │
        used up all its items)   │
   next statement  ◄─────────────┘

Notice the indentation: the else lines up with the for, not with the if inside the loop.

What it is for: searching

Almost every real use is a search: "look through these for something. If you find it, stop. If you get to the end without finding it, do this other thing."

Chapter 14 tested for a prime number with a flag:

n = 91
is_prime = True
for divisor in range(2, n):
    if n % divisor == 0:
        is_prime = False
        break
if is_prime:
    print(n, "is prime")
else:
    print(n, "is not prime")

Output

91 is not prime

With a loop else, the flag disappears:

n = 97
for divisor in range(2, n):
    if n % divisor == 0:
        print(n, "is not prime: it divides by", divisor)
        break
else:
    print(n, "is prime")

Output

97 is prime

Read it as: try every divisor. If one works, report it and stop. If the loop gets through all of them with no break, the number is prime.

Another search, for a character in a string:

text = input("Text: ")
for ch in text:
    if ch.isdigit():
        print("First digit found:", ch)
        break
else:
    print("There are no digits in the text.")

Output

Text: hello world
There are no digits in the text.

Three details

  • An empty loop counts as finishing normally. If the sequence has no items, the block never runs, no break happens, and the else runs. For the prime test with n = 2, range(2, 2) is empty, so 2 is prime is printed, which is correct.
  • It works with while too. The else runs when the condition becomes false, and is skipped after a break.
  • Without a break in the loop, the else is pointless. It would always run, so the code might as well be written after the loop with no else.

Quick check

What does this print? for ch in "abc": with the block if ch == "z": break, followed by else: print("no z")

Show the answer

Answer: no z. The loop looked at every character, never reached the break, and so finished normally.

Leaving two loops with else

Now for the third way promised in section 15.6. The outer block can use the inner loop's else to decide whether to keep going:

for x in range(1, 6):
    for y in range(1, 6):
        if x * y == 12:
            print("Found:", x, y)
            break
    else:
        continue      # the inner loop was NOT broken: go on to the next x
    break             # the inner loop WAS broken: leave the outer loop too

Output

Found: 3 4

Follow the two cases:

  • The inner loop finishes without finding anything. Its else runs, and continue jumps to the next pass of the outer loop, skipping the final break.
  • The inner loop breaks. Its else is skipped, so the next statement is the final break, which ends the outer loop.

This is a well-known Python idiom, and you should be able to read it when you meet it. Many programmers find the flag clearer, and a function with return clearest of all. Use whichever you can explain easily.

Practice 15.7

Predict the output

What does it print?

for n in range(2, 5):
    if n * n > 20:
        print("big", n)
        break
else:
    print("none found")
print("end")

Multiple choice

For which reply does this program print nothing?

word = input("Word: ")
for ch in word:
    if ch == "z":
        break
else:
    print("no break")
Choose one answer

Put the lines in order

Put the lines in order: a search for a divisor with a loop else. The indentation of each line is fixed.

The program in the right order prints:

Target

divides by 5
  1. for divisor in range(2, n):
  2. print("prime")
  3. break
  4. if n % divisor == 0:
  5. n = 35
  6. else:
  7. print("divides by", divisor)

Fix the bug

This should print the first digit of the reply and stop looking. It should print No digit only when the reply has no digit. Now it prints every digit, and No digit after every reply. Fix it.

With the reply x7y9, the program prints the lines below. Your program must print exactly these lines.

Example run

Digit found: 7

Fill in the blank

Fill in the blank so that the program stops both loops at the first pair that adds up to 9.

for x in range(1, 6):
    for y in range(1, 6):
        if x + y == 9:
            print(x, y)
            break
    else:
        
    break

The finished program prints:

Target

4 5

15.8 Mixing for and while

Any loop can be nested in any other. Choose each one by the rule from Chapter 14: "for each" or "until".

A for inside a while

A menu that keeps going until the user leaves is a while. Each action it performs may contain a for:

while True:
    n = int(input("Table for which number (0 to stop)? "))
    if n == 0:
        break
    for i in range(1, 4):
        print(f"  {n} x {i} = {n * i}")
print("Goodbye.")

Output

Table for which number (0 to stop)? 3
  3 x 1 = 3
  3 x 2 = 6
  3 x 3 = 9
Table for which number (0 to stop)? 5
  5 x 1 = 5
  5 x 2 = 10
  5 x 3 = 15
Table for which number (0 to stop)? 0
Goodbye.

The break here sits directly in the while block, not inside the for, so it ends the while.

A while inside a for

For each number from 20 to 24, count how many times it can be halved before it becomes odd. The outer loop is "for each number"; the inner loop is "until it is odd":

for n in range(20, 25):
    value = n
    halvings = 0
    while value % 2 == 0:
        value //= 2
        halvings += 1
    print(n, "can be halved", halvings, "times")

Output

20 can be halved 2 times
21 can be halved 0 times
22 can be halved 1 times
23 can be halved 0 times
24 can be halved 3 times

Two things here are worth copying:

  • halvings = 0 is inside the outer loop but before the inner one. It must be reset for each new number. An accumulator belongs just outside the loop that fills it. Put it above the outer loop and the counts would run together. Put it inside the inner loop and it would reset on every halving.
  • The work is done on a copy, value. Changing n itself would not upset the for loop (Chapter 14 showed that), but the last line needs the original number for its message.

Primes up to a limit

Nested loops and the loop else together list every prime below 30. The outer loop picks a candidate; the inner loop searches for a divisor:

for n in range(2, 30):
    for divisor in range(2, n):
        if n % divisor == 0:
            break
    else:
        print(n, end=" ")
print()

Output

2 3 5 7 11 13 17 19 23 29

The inner loop, with its else, is the complete prime test from section 15.7. The outer loop simply runs that test for each candidate. Building a bigger program by wrapping a loop around something that already works for one case is a very good way to work.

Practice 15.8

Predict the output

What does it print?

for start in range(3, 6):
    value = start
    steps = 0
    while value > 1:
        value //= 2
        steps += 1
    print(start, steps)

Write code

Digit sums. Ask for a first whole number, then for a last whole number. For every number from the first to the last, both included, print one line: the number, one space, and the sum of its digits. For 98 the line is 98 17. The numbers are never negative.

With the replies 17 then 21, the program prints the lines below. Your program must print exactly these lines.

Example run

17 8
18 9
19 10
20 2
21 3

15.9 How much work is a nested loop?

Because the passes multiply, nested loops grow quickly. Suppose both loops run n times:

n One loop Two nested loops Three nested loops
10 10 100 1 000
100 100 10 000 1 000 000
1 000 1 000 1 000 000 1 000 000 000
10 000 10 000 100 000 000 1 000 000 000 000

Chapter 13 said Python manages some tens of millions of simple passes per second. So two nested loops over 1 000 items take a moment. Over 10 000 items they take several seconds. Three nested loops over 1 000 items would take around a minute, and over 10 000 items, many hours.

Making the input ten times bigger makes a double loop take a hundred times longer. Programmers say such a loop takes time proportional to n squared.

Three habits keep nested loops under control:

  1. Do not repeat work in the inner loop. Anything that does not change in the inner loop should be calculated once, outside it.
  2. Stop as soon as you can. A break at the first answer can save most of the work.
  3. Shrink the inner range. The prime test does not need divisors all the way up to n. If n has a divisor at all, it has one no bigger than its square root, so range(2, int(n ** 0.5) + 1) is enough. For a number near a million, that is about a thousand checks instead of a million.

Later you will meet data structures that replace an entire inner loop with a single instant lookup → Chapter 37. For now, the lesson is simply to notice when you are nesting, and to ask how big the numbers will get.

Practice 15.9

Multiple choice

A program with two nested loops over the same items needs about 1 second for 2 000 items. About how long does it need for 20 000 items?

Choose one answer

15.10 Common mistakes

The mistake What you see The fix
The line-ending print() inside the inner loop Every item on its own line Dedent it to the outer block
No line-ending print() at all The whole grid on one long line Add print() after the inner loop
The same variable for both loops Confusing results; the outer value is overwritten Use different names: row and column, i and j
A counter reset in the wrong place Totals that keep growing, or that are always tiny Reset it just before the loop that fills it
Expecting break to leave both loops The outer loop carries on A flag, a function with return, or the loop else
A loop else indented under the if The "not found" branch runs on every pass Line the else up with for or while
A loop else when the loop has no break The else always runs Remove the else
The inner range starts at 0 when pairing Every pair twice, and items paired with themselves Start the inner loop at i + 1
The outer loop variable used in the inner range by mistake, or forgotten The wrong shape Make a row-by-row table first
Unnecessary nesting A program that slows to a crawl on larger inputs Ask whether the inner loop is really needed

Practice 15.10

Fix the bug

For each row of a 3-by-3 grid, this should count the positions where row + column is even. The correct counts are 2, 1 and 2. Now every count is too small. Fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

Row 1 has 2
Row 2 has 1
Row 3 has 2

15.11 Choosing the right loop: a summary

Three chapters of loops come down to this:

You want to... Use
do something for each character, item or number in a known range for
repeat a fixed number of times for _ in range(n)
repeat until something happens, without knowing how long while
repeat until the user decides to stop while True with break
work with rows and columns, or every pair nested loops
search, and act on "not found" a loop with break and else
stop early break
skip the rest of this pass continue

15.12 Putting it together

15.13 How nested loops work inside Python

+ Practice

Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.

Questions

Check yourself

In a nested loop, how many times does the inner loop run from start to finish?

Show the answer

Once, completely, for every single pass of the outer loop.

Check yourself

An outer loop runs 6 times and its inner loop runs 4 times per pass. How many times does the innermost line run?

Show the answer

24 times (6 × 4).

Check yourself

In a grid-printing loop, where does the bare print() go, and what does it do?

Show the answer

In the outer block, after the inner loop. It ends the current line, so the next row starts on a new line.

Check yourself

What does the inner range(row) do in a triangle pattern?

Show the answer

It makes the inner loop run row times, so each row has as many items as its row number.

Check yourself

Why does for j in range(i + 1, n) avoid pairing an item with itself and avoid listing a pair twice?

Show the answer

j only takes values greater than i. So j is never equal to i, and of the two orders of any pair, only the one with the smaller index first is ever produced.

Check yourself

Which loop does a break inside the inner loop end?

Show the answer

Only the inner loop. The outer loop continues with its next pass.

Check yourself

When does a loop's else block run? When is it skipped?

Show the answer

It runs when the loop ends normally: the sequence is used up, or the while condition becomes false. It is skipped when the loop is left by break.

Check yourself

Why is a loop else pointless when the loop contains no break?

Show the answer

Without a break the loop always ends normally, so the else always runs. The code could just be placed after the loop.

Check yourself

In section 15.8, why is halvings = 0 placed inside the outer loop and not before it?

Show the answer

It must start again from zero for each number. Before the outer loop it would be set only once, and the counts for different numbers would add together.

Check yourself

A double loop takes 2 seconds for 5 000 items. Roughly how long will it take for 50 000 items?

Show the answer

Ten times the items means about a hundred times the work: roughly 200 seconds.

Predict the output

Predict the output

for i in range(1, 4):
    for j in range(i):
        print(i, end="")
    print()

Predict the output

count = 0
for i in range(3):
    for j in range(4):
        if j == 2:
            break
        count += 1
print(count)

Predict the output

for i in range(3):
    for j in range(3):
        if i == j:
            continue
        print(i, j, end=" | ")
print()

Predict the output

for n in [4, 9, 7]:
    for d in range(2, n):
        if n % d == 0:
            print(n, "has divisor", d)
            break
    else:
        print(n, "has none")

Predict the output

total = 0
for i in range(1, 4):
    j = i
    while j > 0:
        total += j
        j -= 1
print(total)

Fix the bug

Fix the bug

This should print a 3-by-4 block of #. It prints twelve separate lines.

The program prints the lines below. Your program must print exactly these lines.

Example run

####
####
####

Fix the bug

This should print a triangle with 1, 2, 3, 4 stars. Every row has 4 stars.

The program prints the lines below. Your program must print exactly these lines.

Example run

*
**
***
****

Fix the bug

This should print the total of each row of a 3-by-3 multiplication grid: 6, 12, 18. It prints 6, 18, 36.

The program prints the lines below. Your program must print exactly these lines.

Example run

6
12
18

Fix the bug

This should print No vowels only when the word has none. For "rhythm" it prints No vowels six times.

The program prints the lines below. Your program must print exactly these lines.

Example run

No vowels

Fix the bug

This should stop at the first pair that adds up to 7. It prints several pairs.

The program prints the lines below. Your program must print exactly these lines.

Example run

2 5

Fix the bug

This should print each pair of different letters once: ab ac bc. It prints nine pairs.

The program prints the lines below. Your program must print exactly these lines.

Example run

ab ac bc

Coding problems

Write code · Easy

Rectangle. Ask for a number of rows and columns and print a rectangle of # characters, using nested loops.

Ask for the rows first, then the columns. Print one line for each row, with the # characters side by side and nothing between them.

With the replies 3 then 8, the program prints the lines below. Your program must print exactly these lines.

Example run

########
########
########

Write code · Easy

Number square. Print a 4-by-4 square in which every row is 1 2 3 4.

Print four lines. On each line, the numbers are separated by one space. A space at the end of a line does not matter.

The program prints the lines below. Your program must print exactly these lines.

Example run

1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

Write code · Easy

Count up triangle. Print a triangle five rows high in which row n contains the number n repeated n times, separated by spaces.

Print five lines. On each line, the numbers are separated by one space. A space at the end of a line does not matter.

The program prints the lines below. Your program must print exactly these lines.

Example run

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Write code · Medium

Times tables. Print the multiplication tables from 1 to 9 as a neat 9-by-9 grid with the columns lined up.

Print nine lines. Line 1 holds 1 times 1 up to 1 times 9, line 2 holds 2 times 1 up to 2 times 9, and so on.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

  1  2  3  4  5  6  7  8  9
  2  4  6  8 10 12 14 16 18
  3  6  9 12 15 18 21 24 27
  4  8 12 16 20 24 28 32 36
  5 10 15 20 25 30 35 40 45
  6 12 18 24 30 36 42 48 54
  7 14 21 28 35 42 49 56 63
  8 16 24 32 40 48 56 64 72
  9 18 27 36 45 54 63 72 81

Write code · Medium

Hollow square. Ask for a size and print a square that has stars only on its border and spaces inside.

Print size lines of size characters each. Use * on the border and one space for each inside position.

With the reply 5, the program prints the lines below. Your program must print exactly these lines.

Example run

*****
*   *
*   *
*   *
*****

Write code · Medium

Handshakes. Five people named by the letters VWXYZ each shake hands once with every other person. Print every handshake and the total number.

Print every handshake on one line in the form V-W, with one space between handshakes, in the order the loops make them. Then print a second line: Handshakes:, a space and the total.

The program prints the lines below. Your program must print exactly these lines.

Example run

V-W V-X V-Y V-Z W-X W-Y W-Z X-Y X-Z Y-Z
Handshakes: 10

Write code · Medium

First repeated letter. Ask for a word and print the first letter that appears more than once, or a message if no letter repeats. Use a loop else.

Go through the word from the left and stop at the first letter that appears again later in the word. Print First repeated letter: and the letter, or print No letter repeats. The tests use lower-case words.

With the reply programming, the program prints the lines below. Your program must print exactly these lines.

Example run

First repeated letter: r

Write code · Hard

Right-angled triangles. Find every set of whole numbers x, y, z with x < y < z and z at most 30 where x * x + y * y == z * z. Print each set and the total.

Print each set on its own line as three numbers with one space between them, in the order the loops find them. Then print a last line: Total:, a space and the number of sets.

The program prints the lines below. Your program must print exactly these lines.

Example run

3 4 5
5 12 13
6 8 10
7 24 25
8 15 17
9 12 15
10 24 26
12 16 20
15 20 25
18 24 30
20 21 29
Total: 11

Write code · Hard

Diamond. Ask for a size n and print a diamond of stars with n rows in its top half (the widest row has 2 * n - 1 stars) and n - 1 rows below.

Put spaces before the stars only, never after them. The widest row starts at the left edge.

With the reply 4, the program prints the lines below. Your program must print exactly these lines.

Example run

   *
  ***
 *****
*******
 *****
  ***
   *

Write code · Hard

Perfect numbers. A perfect number equals the sum of its divisors, not counting itself: 6 = 1 + 2 + 3. Find every perfect number below 10 000.

Print the perfect numbers from the smallest to the largest. A simple program needs several seconds here, so wait for it to finish.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

6 28 496 8128

Chapter project: Tournament planner

Project

Plan a small tournament. Every team has a one-letter name, and every team plays every other team once. Write a program that asks for the team letters as one piece of text, such as KLMN.

  1. First check the letters. Go through the text from the left. If a letter appears again later in the text, print Repeated letter:, a space and that letter, and print nothing else. Report only the first such letter.
  2. If no letter is repeated, print every match on its own line in the form Match 1: K v L. The match numbers count up from 1. The matches come in this order: the first team against each later team, then the second team against each later team, and so on.
  3. After the matches, print a last line: Matches:, a space and the number of matches.

Use nested loops for the check and for the list of matches. Remember that break leaves one loop only.

With the reply KLMN, the program prints the lines below. Your program must print exactly these lines.

Example run

Match 1: K v L
Match 2: K v M
Match 3: K v N
Match 4: L v M
Match 5: L v N
Match 6: M v N
Matches: 6