Introduction:

A loop in programming is a structure that allows you to repeat a block of code multiple times. For example, if you want to print something 10 times, you can use a loop to automate that repetition instead of writing the same print statement 10 times.

But what if you need to repeat a block of code inside another repeating block? That’s where nested loops come in. With nested loops, one loop runs inside another. The outer loop controls how many times the inner loop will run completely, and the inner loop handles the repeated actions that need to happen within each iteration of the outer loop.

For example, if you wanted to create a grid of stars, you could use a nested loop: one loop for the rows and another loop for the stars in each row.

Example:

for i in range(3): # Outer loop for rows
    for j in range(5): # Inner loop for stars in each row
        print("*", end="")
    print() # Moves to the next line after each row

Why Use Nested Loops?

Nested loops are incredibly useful when you need to work with data or patterns that involve multiple layers. For example, imagine you want to print a grid, where there are rows and columns. Each row contains multiple columns of data. With a nested loop:

  • The outer loop controls the rows.
  • The inner loop controls the columns.

This kind of structure is especially helpful for:

  • Creating grids (like in the star pattern example).
  • Processing tables (e.g. spreadsheets with rows and columns of data).
  • Generating patterns (e.g. triangles, pyramids, checkerboards).
  • Working with multi-dimensional data (such as matrices in mathematics or lists within lists in Python).

Expanded Example

Let’s revisit our grid of stars example:

for i in range(3): # Outer loop for rows
    for j in range(5): # Inner loop for stars in each row
        print("*", end="")
    print() # Moves to the next line after each row
  • Outer loop: The for i in range(3) runs 3 times, meaning we will print 3 rows in total.
  • Inner loop: For each time the outer loop runs, the inner loop for j in range(5) runs 5 times, printing 5 stars on the same line.
  • print() statement: After each inner loop finishes printing a row of 5 stars, we go back to the outer loop where the print() statement moves to the next line so the next row can start.

Here’s a breakdown of what happens during each loop cycle:

  1. In the first cycle of the outer loop (i = 0), the inner loop prints 5 stars (*****), then moves to the next line.
  2. In the second cycle of the outer loop (i = 1), the inner loop again prints 5 stars, and moves to the next line.
  3. In the third cycle of the outer loop (i = 2), the inner loop prints 5 stars for the last time, and the program ends.

In total, we get a 3x5 grid of stars, like this:

*****
*****
*****

By adjusting the ranges in either loop, we can change the number of rows and stars, allowing us to create different grid sizes or patterns. Nested loops are a versatile and powerful tool for handling repetitive tasks with multiple layers of complexity!

Predict:

Take a look at the following code and think about what the output will be. What will the nested loops do?

for i in range(2):
    for j in range(3):
        print("Row", i, "Column", j) 

Your task: Predict the output before running any code. How many rows and columns will this print?

Run:

Now, let's run a similar example in the embedded Python IDE. This code will generate a pattern of stars using nested loops. Run the code to see the pattern it creates.

This code prints a grid of stars with 4 rows and 6 stars in each row. Notice how the inner loop runs multiple times for each iteration of the outer loop.

Investigate:

Now let's explore a slightly different example. Investigate how changing the loop ranges affects the output.

Instructions: Run the code above and observe the output. Notice how the number of stars increases with each row. Try changing the range in the outer loop or the inner loop to see how the pattern changes.

Modify:

Here’s a piece of code that is meant to print a triangle pattern of stars, but there’s a mistake in the inner loop. Can you find the error and fix it?

Hint: The stars aren’t being printed in a straight line. Look at the placement of print() and see if something needs adjusting. Use the example in the 'Investigate' section above to help.

Scroll to Top