Python Arena
Step 3 of 4

Loops inside loops

The body of a loop can hold any statements, another loop included. A loop inside a loop is called a nested loop. The inner loop runs all its rounds during each single round of the outer loop.

This program asks for sizes until the user types 0. For each size, an inner loop builds a row of that many blocks, one block per round:

while True:
    size = int(input("Size: "))
    if size == 0:
        break
    row = ""
    while size > 0:
        row += "[]"
        size -= 1
    print(row)
Input
3
1
0
Output
Size: 3
[][][]
Size: 1
[]
Size: 0

("[]" * size would build the same row. Here the inner loop shows how loops fit inside each other.)

Read it from the outside in. The outer loop asks for a size. The inner loop, indented one more level, builds the row. When the inner loop is done, the rest of the outer loop's body prints the row, and the outer loop starts its next round.

How many times?

Two counters show how often each line runs:

outer = 1
while outer <= 3:
    inner = 1
    while inner <= 2:
        print(f"outer {outer}, inner {inner}")
        inner += 1
    outer += 1
Output
outer 1, inner 1
outer 1, inner 2
outer 2, inner 1
outer 2, inner 2
outer 3, inner 1
outer 3, inner 2

The inner loop runs completely, two rounds, in each of the three rounds of the outer loop: six lines in all. Note where inner = 1 is: inside the outer loop, so the inner counter starts again from 1 every time. The next step looks at that closely.

break and continue in nested loops

break and continue work on the innermost loop they're in. In the first example, the break is in the outer loop, so it ends the whole thing. A break in an inner loop would end only the inner loop: the outer loop would carry on with the rest of its body and its next round. In the same way, continue in an inner loop skips to the next round of the inner loop.

Your task

Challenge 1 of 3

What does this program print? Type each line it prints.

Challenge 2

Write a program that asks for a size and prints a grid of coordinates: one line per row, and on each line the pair (row,column) for every column, with spaces between the pairs. Rows and columns count from 1.

Size: 3
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

Challenge 3

Write a program that asks for words with the prompt Word: until the user types end. For each word, it prints the word with every letter doubled.

Word: cat
ccaatt
Word: no
nnoo
Word: end