CodingNic

Loops and Iteration

Nested Loops

Loops and Iteration 22 min read

Nested Loops

Nested Loops

Sometimes one loop is not enough.

You may want a loop inside another loop.

This is called a nested loop.

What Is a Nested Loop?

A nested loop is a loop inside another loop.

The inside loop runs fully each time the outside loop runs once.

Simple Example

python
for row in range(1, 4):
    for column in range(1, 3):
        print("Row", row, "Column", column)

How This Example Works

The outside loop controls rows.

The inside loop controls columns.

Step by step:

  • Row 1 starts
  • Column 1 runs
  • Column 2 runs
  • Row 2 starts
  • Column 1 runs
  • Column 2 runs
  • Row 3 starts
  • Column 1 runs
  • Column 2 runs

Output

text
Row 1 Column 1
Row 1 Column 2
Row 2 Column 1
Row 2 Column 2
Row 3 Column 1
Row 3 Column 2

Another Example

python
for letter in "AB":
    for number in range(1, 4):
        print(letter, number)

Why Nested Loops Matter

Nested loops are useful for:

  • Tables
  • Patterns
  • Grids
  • Menus
  • Comparing items

Pattern Example

python
for row in range(3):
    for star in range(4):
        print("*", end="")
    print()

Code Along

python
for day in range(1, 3):
    for task in range(1, 4):
        print("Day", day, "Task", task)

Mini Challenge

Build a pattern printer.

Steps:

  • Use a nested loop
  • Print 3 rows
  • Each row should show:
    ***

Expected output:

text
***
***
***

Real World Use Case

Programs use nested loops for seating charts, game boards, calendars, reports, and tables.

Quiz

  1. What is a nested loop?
  2. Which loop runs many times inside the other?
  3. What are nested loops useful for?
  4. Can you use a for loop inside another for loop?

Assignment

Create a program that prints:

text
1 2 3
1 2 3
1 2 3

Use nested loops.

Summary

You learned that nested loops are loops inside loops and are useful for patterns, tables, and repeated groups of tasks.