Python · Module 03: Loops & IterationTutorial 8 of 30

3.2 Nested Loops, Pattern Printing & Loop-Else

Build rock-solid loop intuition! Visualize how outer and inner loops work like a clock's hour and minute hands, print classic star/number patterns, and learn Python's unique for-else search idiom.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. The Clock Analogy for Nested Loops

Whenever you put one loop inside another loop, freshers often lose track of which variable changes first. Think of a wall clock:

  • The outer loop (row) is the Hour hand — it moves slowly (1 tick).
  • The inner loop (col) is the Minute hand — it completes a full rotation for every single tick of the outer loop!
Visual: Nested Loops = Clock Hours (Outer `row`) × Minutes (Inner `col`)
for row in range(3): for col in range(3)(0,0)(0,1)(0,2)(1,0)(1,1)(1,2)(2,0)(2,1)(2,2)Total runs = 3 × 3 = 9 iterationsTriangle: for col in range(row + 1)★★★★★★Inner loop shrinks/grows based on outer `row`!
PYTHON
# Multiplication table (1 to 3)
for row in range(1, 4):
    for col in range(1, 4):
        print(f"{row * col:2d}", end=" ")
    print()  # Move to a new line after each full row!

# Output:
#  1  2  3
#  2  4  6
#  3  6  9

2. Building Classic Patterns (Without Guessing!)

The secret to ANY pattern problem in college exams or interviews is a 2-question formula:

  1. Outer loop (row): How many rows are there?
  2. Inner loop (col): In row r, how many symbols (or spaces) do I print?
PYTHON
# 1) Right-angled star triangle (4 rows)
for row in range(1, 5):
    print("*" * row)
# *
# **
# ***
# ****

# 2) Centered pyramid (4 rows)
rows = 4
for row in range(1, rows + 1):
    spaces = " " * (rows - row)
    stars  = "*" * (2 * row - 1)
    print(spaces + stars)
#    *
#   ***
#  *****
# *******

(Notice how Python's string multiplication "*" * row replaces an entire inner loop cleanly!)


3. Interactive Trace: Watching Outer & Inner Loop Variables

Click Next to watch how col completes all of its turns before row increments by 1:

Tracing a 2×2 Nested Loop
Interactive Line-by-Line Execution Trace · Step 1 of 8
1→for row in range(2):
2 for col in range(2):
3 print(f"({row},{col})")
Variables in Memory
row0int
Console Output
(nothing printed yet)
What just happened: Outer loop starts: row = 0.

4. Python's Hidden Gem: for ... else (The Clean Search Pattern)

Did you know Python loops can have an else: block?

  • The else: block runs ONLY if the loop finished normally without hitting break!
  • Think of else: on a loop as meaning "if no break happened (not found)":
PYTHON
numbers = [10, 25, 42, 70]
target = 99

for num in numbers:
    if num == target:
        print("Found target!")
        break
else:
    print("Target was NOT found in the list.")

(Zero found = False flag variables needed!)


5. Beginner Trap: break Only Exits the INNERMOST Loop!

If you put break inside an inner loop, it only stops the inner loop — the outer loop keeps going. To exit both cleanly, wrap the search in a function and use return (which we will cover in Module 5!).


Quick Quiz: Module 3.2 — Nested Loops & Patterns

Q1.How many times does `print('Hi')` run?
for i in range(4):
    for j in range(3):
        print('Hi')
Q2.When does the `else:` block attached to a `for` loop execute?
Q3.What does `print("#" * 4)` output?

Keep Exploring: Related Lessons & Tools

All Courses →