▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Nested loops and patterns
Loops inside loops: tables and star patterns from interviews.
🎬 Video version coming soon — read it now
A nested loop is a loop inside another loop. For every round of the outer loop, the inner loop runs completely.
Output:
end=" " tells print to finish with a space instead of a new line, so items stay on one row. The empty print() then moves to the next line.
Times tables grid
:4 pads each number to 4 characters so the columns line up.
Star patterns (interview favourites)
These appear in many campus placement tests. Right triangle:
Pyramid:
How to solve any pattern
- Draw the output for a small n, such as 3 or 4.
- For each row, count the spaces and stars (or numbers).
- Write those counts as a formula of the row number
i. - Code it, then test with n = 1 and a large n.
Watch the cost
A loop of 1,000 inside a loop of 1,000 runs a million times. Nested loops are fine for small data, but they're the first place to look when a program is slow. You'll learn more in the Async & Performance course.
In one line
In a nested loop the inner loop runs fully for every outer round, which is how grids, tables and star patterns are built.
Share with a friend