Kickstart 2020 with new opportunities! - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The for loop
The while loop
Nested loops
14. Nested for loops – explanation
break and continue
Summary

Instruction

Good. Let's take a look at the code again and analyze how it works:

for i in range (1, 11):
for j in range (1, 11):
print(i, 'x', j, '=', i*j)


We start with i equal to 1. Having i == 1, we enter the inner loop, where we gradually increment the value of j from j == 1 to j == 10. Each time, we print 'i x j = ...'. Once we're done with j == 10, we return to the outer loop. Now, i == 2, and we enter the inner loop again, and iterate from j == 1 to j == 10. Next, we go back to the outer loop and the procedure continues until i == 10 and j == 10:

When using nested loops, you should be careful not to make them too complicated. As you can see above, two loops, one inside another, that increment two variables from 1 to 10 will result in 10 * 10 = 100 iterations. The number of iterations increases quickly! For small programs such as this, the impact on performance will be negligible, but that may not be the case for larger programs.

Exercise

Use nested loops to print the following output:

111111111
222222222
333333333
444444444
555555555
666666666
777777777
888888888
999999999


Tip: You can use the + operator to concatenate strings.

Stuck? Here's a hint!

First, you will need a string variable where you will add characters to be printed on the current line.

If your outer loop uses a variable named i, then your inner loop should use range(0, 9). In the inner loop, all you have to do is add the value of i to the string variable. You have to cast the integer i to a string first with: str(i).

Finally, in the outer loop, after the inner loop finishes, print the string variable, and then set it to the empty string '', clear it for reuse in the next iteration.