Overview
Explore how nested loops, break, continue, and else interact to control iteration flow.
Analogy
Nested Russian dolls: outer loop is the big doll, inner loop is each smaller doll inside.
Step-by-step
- Outer loop runs n times; inner loop runs m times each → O(n×m) steps.
- break in inner loop only exits the inner loop.
- continue skips the rest of the current iteration.
- for/while else runs only when no break occurred.
Visual
for i in range(3): for j in range(2): print(i,j) → (0,0)(0,1)(1,0)(1,1)(2,0)(2,1)
Common mistakes
- Thinking break exits all loops (use a flag or refactor).
- Misplacing else under for vs if.
Practice questions
- Print a star triangle using nested loops.
- Use for-else to search and report if an item is missing.
Time
O(n×m) for two nested loops