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.
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.
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.
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.