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

for multiplier in range (5, 8): for i in range (1, 11):

print i, "x", multiplier, " = ", i * multiplier print

This inner loop prints a single table

This outer loop runs 3 iterations, with values 5, 6, 7

Notice that we had to indent the inner loop and the print statement an extra four spaces from the beginning of the outer for loop. This program will print the 5 times, 6 times, and 7 times tables, up to 10 for each table:

>>>

------- RESTART -------------------

>>>

1 x

5

=

5

2 x

5

=

10

3 x

5

=

15

4 x

5

=

20

5 x

5

=

25

6 x

5

=

30

7 x

5

=

35

8 x

5

=

40

9 x

5

=

45

10 x

5

= 50

1 x

6

=

6

2 x

6

=

12

3 x

6

=

18

4 x

6

=

24

5 x

6

=

30

6 x

6

=

36

7 x

6

=

42

8 x

6

=

48

9 x

6

=

54

10 x

6

= 60

1 x

7

=

7

2 x

7

=

14

3 x

7

=

21

4 x

7

=

28

5 x

7

=

35

6 x

7

=

42

7 x

7

=

49

8 x

7

=

56

9 x

7

=

63

10 x

7

= 70

Although you might think it's pretty boring, a good way to see what's going on with nested loops is to just print some stars to the screen and count them. We'll do that in the next section.

Was this article helpful?

+1 0
100 Bowling Tips

100 Bowling Tips

Playing bowling with your friends can help you decide if it is indeed the hobby that you want to invest your time on today. Aside from that, it can help you get a better feel of the sport. More importantly, when you play with your friends, it would become a more fun activity, which you can look forward to each week.

Get My Free Ebook


Responses

  • arthur
    How to enclose a loop within another loop in python?
    8 years ago

Post a comment