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
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
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
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
for row in range(3):
for star in range(4):
print("*", end="")
print()
Code Along
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:
***
***
***
Real World Use Case
Programs use nested loops for seating charts, game boards, calendars, reports, and tables.
Quiz
- What is a nested loop?
- Which loop runs many times inside the other?
- What are nested loops useful for?
- Can you use a
forloop inside anotherforloop?
Assignment
Create a program that prints:
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.