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)
3
1
0Size: 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
outer 1, inner 1
outer 1, inner 2
outer 2, inner 1
outer 2, inner 2
outer 3, inner 1
outer 3, inner 2The 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.