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.
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!
# 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:
- Outer loop (
row): How many rows are there? - Inner loop (
col): In rowr, how many symbols (or spaces) do I print?
# 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:
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 hittingbreak! - Think of
else:on a loop as meaning "if no break happened (not found)":
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
for i in range(4):
for j in range(3):
print('Hi')Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.