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
forloop inside anotherforloop. - Outer loop controls rows / groups.
- Inner loop controls columns / items per row.
Basic skeleton
Example 1: 3x4 star grid
Example 2: coordinate pairs
Iteration count rule
If outer runsm times and inner runs n times each:
- inner body executes
m * ntimes
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
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
- Print 5x5 grid of
#. - Print numbers 1 to 3 in each row for 4 rows.
- Predict total prints:
Answer idea
- Total =
0 + 1 + 2 + 3 = 6
