Quiz 2

Nested Loops & Loop Patterns

1520 words
8 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Nested Loops & Loop Patterns > **Why read this?** One loop is powerful. A loop inside another loop unlocks 2D problems — multiplication tables, grid traversal, pattern printing, and matrix operations.

Nested Loops & Loop Patterns

Why read this? One loop is powerful. A loop inside another loop unlocks 2D problems — multiplication tables, grid traversal, pattern printing, and matrix operations. Nested loops are how you handle anything with rows AND columns.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Write nested for loops for 2D iteration
  2. Print patterns (triangles, rectangles, pyramids) using nested loops
  3. Traverse 2D data structures (matrices, grids)
  4. Understand time complexity: O(n²) vs O(n)
  5. Choose the right loop pattern for a problem

📋 Prerequisites

  • For Loops & range() — Must be comfortable with for and range().
  • Basic problem-solving skills.

📖 Core Content

11.1 What Problem Do Nested Loops Solve?

Intuition: A single loop handles a line. A nested loop handles a grid. Think of a calendar: the outer loop goes through months (1-12), the inner loop goes through days (1-28/30/31). For each month, you iterate through all its days.

11.2 Basic Nested For Loop

python
# runnable
for i in range(1, 4):
    for j in range(1, 4):
        print(f"i={i}, j={j}")
Output:
pseudo
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
How it executes:
  1. Outer loop: i=1
  2. Inner loop runs fully: j=1,2,3 (all three iterations)
  3. Outer loop: i=2
  4. Inner loop runs fully again: j=1,2,3
  5. Continue... Total iterations: 3 × 3 = 9 Diagram Rendering diagram

11.3 Multiplication Table with Nested Loops

python
# runnable
for i in range(1, 11):
    for j in range(1, 11):
        print(f"{i * j:4d}", end="")
    print()  # newline after each row
Output:
pseudo
   1   2   3   4   5   6   7   8   9  10
   2   4   6   8  10  12  14  16  18  20
   3   6   9  12  15  18  21  24  27  30
   4   8  12  16  20  24  28  32  36  40
   5  10  15  20  25  30  35  40  45  50
   6  12  18  24  30  36  42  48  54  60
   7  14  21  28  35  42  49  56  63  70
   8  16  24  32  40  48  56  64  72  80
   9  18  27  36  45  54  63  72  81  90
  10  20  30  40  50  60  70  80  90 100

11.4 Worked Example 1: Right-Angled Triangle Pattern

python
# runnable
n = 5
for i in range(1, n + 1):
    for j in range(i):
        print("*", end="")
    print()
Output:
pseudo
*
**
***
****
*****
Trace (n=5):
ij runsStars printed
10 (once)*
20,1**
30,1,2***
40,1,2,3****
50,1,2,3,4*****

11.5 Worked Example 2: Pyramid Pattern

python
# runnable
n = 5
for i in range(1, n + 1):
    # Print spaces
    for j in range(n - i):
        print(" ", end="")
    # Print stars
    for k in range(2 * i - 1):
        print("*", end="")
    print()
Output:
pseudo
    *
   ***
  *****
 *******
*********

11.6 Worked Example 3: Matrix Addition

python
# runnable
# Two 3x3 matrices
A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
B = [[9, 8, 7],
     [6, 5, 4],
     [3, 2, 1]]
result = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]
for i in range(3):
    for j in range(3):
        result[i][j] = A[i][j] + B[i][j]
# Print result
for row in result:
    print(row)
Output:
pseudo
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

11.7 Worked Example 4: Finding Maximum in Each Row

python
# runnable
matrix = [
    [3, 8, 1],
    [9, 2, 7],
    [4, 6, 5]
]
for i in range(len(matrix)):
    max_val = matrix[i][0]
    for j in range(1, len(matrix[i])):
        if matrix[i][j] > max_val:
            max_val = matrix[i][j]
    print(f"Row {i}: max = {max_val}")
Output:
pseudo
Row 0: max = 8
Row 1: max = 9
Row 2: max = 6

11.8 Worked Example 5: Nested While Loop — GCD Table

python
# runnable
print("GCD Table (1-5):")
for a in range(1, 6):
    for b in range(1, 6):
        x, y = a, b
        while y != 0:
            x, y = y, x % y
        print(f"gcd({a},{b})={x}", end=" ")
    print()
Output:
pseudo
GCD Table (1-5):
gcd(1,1)=1 gcd(1,2)=1 gcd(1,3)=1 gcd(1,4)=1 gcd(1,5)=1
gcd(2,1)=1 gcd(2,2)=2 gcd(2,3)=1 gcd(2,4)=2 gcd(2,5)=1
gcd(3,1)=1 gcd(3,2)=1 gcd(3,3)=3 gcd(3,4)=1 gcd(3,5)=1
gcd(4,1)=1 gcd(4,2)=2 gcd(4,3)=1 gcd(4,4)=4 gcd(4,5)=1
gcd(5,1)=1 gcd(5,2)=1 gcd(5,3)=1 gcd(5,4)=1 gcd(5,5)=5

📐 Key Concepts Reference

PatternOuter LoopInner LoopUse Case
Rectangle n×mrange(n)range(m)Grid, matrix
Trianglerange(n)range(i+1) or range(n-i)Patterns
Pyramidrange(n)spaces + range(2*i+1)Centered patterns
Matrix opsrange(rows)range(cols)Linear algebra
Iterate pairsrange(n)range(m)Comparisons

⚠️ Common Pitfalls

Pitfall 1: Wrong Variable Name in Inner Loop

The mistake: Using i in both outer and inner loop — the inner assignment overwrites the outer counter. Fix: Use different variable names: i for outer, j for inner.

Pitfall 2: Forgetting end="" in print

The mistake: print("*") inside a pattern loop — each star prints on a new line. Fix: Use print("*", end="") to stay on same line, then print() for newline.

Pitfall 3: Off-by-One in Triangle Patterns

The mistake: for j in range(i): producing wrong number of stars. Fix: Trace with a small n (like 3). range(i) gives i iterations (0 to i-1). For row i=1, one star is correct.

Pitfall 4: Performance — Unnecessary Nested Loops

The mistake: Using nested loops when a single loop suffices. Example: Summing all elements of a 2D list requires nested loops. But summing 1 to n doesn't — use formula or single loop. Fix: Think about whether a problem is inherently 2D before nesting.

📝 Practice Questions

Q1: How many times does "Hi" print?
python
for i in range(3):
    for j in range(4):
        print("Hi")
Answer: 12 times (3 outer × 4 inner = 12) Q2: What does this pattern look like?
python
for i in range(5, 0, -1):
    for j in range(i):
        print("*", end="")
    print()
Answer:
pseudo
*****
****
***
**
*
Inverted triangle: starts with 5 stars, ends with 1. Q3: Write nested loops to print a chessboard (8×8) of 0s and 1s.
Answer:
python
# runnable
for i in range(8):
    for j in range(8):
        print((i + j) % 2, end=" ")
    print()
Q4: What does this code output?
python
for i in range(1, 4):
    for j in range(1, i+1):
        print(j, end="")
    print()
Answer:
pseudo
1
12
123
Q5: Write nested loops to compute the sum of all elements in a 2D list.
Answer:
python
# runnable
matrix = [1, 2], [3, 4], [5, 6](/courses/may26-python/notes/1%2C%202%5D%2C%20%5B3%2C%204%5D%2C%20%5B5%2C%206)
total = 0
for row in matrix:
    for val in row:
        total += val
print(total)  # 21
Q6: What's wrong with this code?
python
for i in range(3):
    for i in range(2):
        print(i)
Answer: Both loops use i. The inner loop overwrites the outer i. After inner loop finishes, outer i is 1 (last inner value), not 0. This still "works" but is confusing and bug-prone. Always use separate variables. Q7: Write code to print a hollow square of stars (5×5).
Answer:
python
# runnable
n = 5
for i in range(n):
    for j in range(n):
        if i == 0 or i == n-1 or j == 0 or j == n-1:
            print("*", end="")
        else:
            print(" ", end="")
    print()
Q8: How many iterations total?
python
count = 0
for i in range(5):
    for j in range(i+1):
        count += 1
print(count)
Answer: 15 (1+2+3+4+5 = 15). Sum of first n integers = n(n+1)/2 = 5×6/2 = 15. Q9: Write code that prints a number triangle where row i contains the number i repeated i times.
Answer:
python
# runnable
n = 5
for i in range(1, n+1):
    for j in range(i):
        print(i, end="")
    print()
Output:
pseudo
1
22
333
4444
55555
Q10: Write a program to transpose a 3×3 matrix.
Answer:
python
# runnable
A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

for i in range(3):
    for j in range(3):
        print(A[j][i], end=" ")
    print()

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.