Nested For Loops

The body of any loop, can even include…another loop! Here is a super-simple program that generates all the times tables from 0 to 10. The str() function changes a numeric value into a string.

(Times_Table)

Here are two different ways to look at this program. In the first one, we look at the structure of the program – what you can understand by just looking at the program.

In this video, we look at the execution of the program – how it actually works when it’s being run by the computer.

How Many Times Does the Inner Loop Execute?

Try out the following code. How many *’s are printed? Why do you think it prints that many? Try changing the start and end values and see what changing those does to the output.

The outer loop executes 2 times and each time the outer loop executes the inner loop executes 3 times so this will print 2 * 3 = 6 stars.

Note

The formula for calculating the number of times the inner loop executes is the number of times the outer loop repeats multiplied by the number of times the inner loop repeats.

    csp-8-5-1: How many times will this loop print a *?

    for x in range(0, 3):
        for y in range(0, 4):
            print('*')
    
  • 6
  • Remember that the range function will include the start value and all the numbers up to one less than the end value. So the outer loop will execute 3 times ([0,1,2]).
  • 9
  • This would be true if they were both range(0,3). Is that correct?
  • 12
  • The number of times a nested loop executes is the number of times the outer loop executes (3) times the number of the times the inner loop executes (4) so that is 3 * 4 = 12.
  • 16
  • This would be true if both were range(0,4). Is that right?
  • 20
  • This would be true if the range returned all the numbers from start to end, but it does not.

You can add items to a string in the inner loop and then print the strings to make a pattern.

Modify the code above to draw a square of stars.

Write code to print stars in the shape of an empty square of size 4 by 4.

Next Section - Chapter 8 - Summary