Chapter 11. Nested and Variable Loops

 

We already saw that, within the body of a loop (which is a block of code), we can put other things that have their own blocks. If you look at the number-guessing program from chapter 1, you’ll see this:

The outer, light gray block is a while loop block, and the dark gray blocks are if and elif blocks within that while loop block.

You can also put a loop within another loop. These loops are called nested loops.

Nested loops

Remember the multiplication table program you wrote for the “Try it out” section in chapter 8? Without the user-input part, it might look something like this:

multiplier = 5                                   
for i in range (1, 11):                          
    print i, "x", multiplier, "=", i * multiplier

What if we wanted to print three multiplication tables at once? That’s the kind of thing a nested loop is perfect for. A nested loop is one loop inside another loop. For each iteration of the outer loop, the inner loop goes through all of its iterations.

To print three multiplication tables, we’d just enclose the original loop (which prints a single multiplication table) in an outer loop (which runs three times). This makes the program print three tables instead of one. Listing 11.1 shows what the code looks like.

Listing 11.1. Printing three multiplication tables at once

Variable loops

Variable nested loops

Even more variable nested loops

Using nested loops

What did you learn?

Test your knowledge

Try it out