Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • explain nested loop flow
  • print row-column patterns
  • estimate iteration count in nested loops
  • avoid indentation and reset mistakes

What is nested for loop?

  • A for loop inside another for loop.
  • Outer loop controls rows / groups.
  • Inner loop controls columns / items per row.

Basic skeleton

for i in range(rows):
    for j in range(cols):
        # body using i, j

Example 1: 3x4 star grid

for i in range(3):
    for j in range(4):
        print('*', end=' ')
    print()
Output:
* * * *
* * * *
* * * *

Example 2: coordinate pairs

for i in range(1, 4):
    for j in range(1, 3):
        print(f"({i},{j})", end=' ')
    print()

Iteration count rule

If outer runs m times and inner runs n times each:
  • inner body executes m * n times
Exam-style question:
for i in range(2):
    for j in range(3):
        print(i, j)
Total lines = 2 * 3 = 6

Common mistakes

  • wrong indentation makes inner loop separate
  • forgetting print() after inner loop for new row
  • reusing same variable name in outer and inner loop
Wrong:
for i in range(3):
    for i in range(4):
        print(i)
Prefer distinct names (i, j).

Exam hints and traps

  • end=' ' keeps output on same line
  • plain print() moves to next line
  • outer loop index changes slower than inner loop index

Practice

  1. Print 5x5 grid of #.
  2. Print numbers 1 to 3 in each row for 4 rows.
  3. Predict total prints:
for i in range(4):
    for j in range(i):
        print('*')

Answer idea

  1. Total = 0 + 1 + 2 + 3 = 6