Back

Activity 1.17: Nested Loops

divider

Activity 1.17

Nested Loops

Key Concepts

Nested Loops

A Loop Inside a Loop

Just like an if can nest inside another if, a for loop can nest inside another for loop — the inner loop runs all the way through for every single pass of the outer loop.

for row in range(1, 4):
for col in range(1, 4):
print(f"(Row {row}, Col {col})", end=" ")
print()

A Loop Inside a Loop

Terminal window
(Row 1, Col 1) (Row 1, Col 2) (Row 1, Col 3)
(Row 2, Col 1) (Row 2, Col 2) (Row 2, Col 3)
(Row 3, Col 1) (Row 3, Col 2) (Row 3, Col 3)

3 rows × 3 columns each = 9 total prints.

Today's Project: Grids

Grids, tables, and boards all share this same shape: an outer loop for rows, an inner loop for columns.

Today's Objectives

  • Nesting one for loop inside another
  • Tracing how many times the inner loop runs in total
  • Building a multiplication table from nested loops

Key Terms

Nested Loop
A loop written inside the body of another loop.
Outer Loop
The loop that contains another loop inside it.
Inner Loop
The loop nested inside another — it completes fully for every pass of the outer loop.

'F' → Fullscreen

divider

Build

Create a new Python program named 1-17-nested-loops.


Task 1: Row and Column Grid

  • Print a label for every row/column combination in a 3x3 grid.
Nested Loops
for row in range(1, 4):
for col in range(1, 4):
print(f"(Row {row}, Col {col})", end=" ")
print()

Task 2: Multiplication Table

  • Ask for a size, then print a multiplication table of that size using nested loops.
Nested Loops
for row in range(1, 4):
for col in range(1, 4):
print(f"(Row {row}, Col {col})", end=" ")
print()
print()
size = int(input("Enter the size of the table: "))
for num1 in range(1, size + 1):
for num2 in range(1, size + 1):
product = num1 * num2
print(product, end=" ")
print()
divider

Checkpoint

Verify your program works correctly.

Example Output
(Row 1, Col 1) (Row 1, Col 2) (Row 1, Col 3)
(Row 2, Col 1) (Row 2, Col 2) (Row 2, Col 3)
(Row 3, Col 1) (Row 3, Col 2) (Row 3, Col 3)
Enter the size of the table: 3 [Enter]
1 2 3
2 4 6
3 6 9
divider

Reflection

Answer the following questions before submitting your work.

  1. In the Row and Column Grid, how many total times does print() run inside the nested loop?
  2. In the multiplication table, what does num1 represent, and what does num2 represent?
  3. Why does print() (with nothing inside it) appear after the inner loop, but not inside it?
divider

Submit

Submit the required files to the appropriate dropbox.

Activity Complete