Nested loops: fill a whole grid of stars
One loop draws a row. A loop inside a loop draws rows and columns — a whole grid — from just a few lines.
The big idea
A nested loop is a loop inside another loop, so for each step of the outer loop, the inner loop runs all the way through.
See it in code
First, watch how a loop inside a loop takes turns. For every row the outer loop holds, the inner loop runs all the way through its col values before the outer loop moves on:
for row in range(2):
for col in range(3):
print("row", row, "col", col)row 0 col 0 row 0 col 1 row 0 col 2 row 1 col 0 row 1 col 1 row 1 col 2
Row 0 runs through all three columns, then row 1 does the same. That's the whole idea: the inner loop runs fully for each step of the outer loop.
Now use both counters to build a position. col decides how far across, row decides how far down — so every pair (row, col) becomes its own spot:
for row in range(2):
for col in range(3):
print("star at x", 100 + col * 100, "y", 120 + row * 130)star at x 100 y 120 star at x 200 y 120 star at x 300 y 120 star at x 100 y 250 star at x 200 y 250 star at x 300 y 250
The y stays put while x marches across a row, then y jumps down for the next row. Hand those x's and y's to real stars and you get a grid.
Same two loops, now on the canvas — a grid of stars, 3 rows with 4 in each. col sets the x and row sets the y, exactly like the warm-up:
from art import Canvas, star
screen = Canvas.create()
Canvas.fill(screen)
for row in range(3):
for col in range(4):
star(screen, 100 + col * 100, 120 + row * 130, size=45)
3 rows times 4 columns is 12 stars — and we only wrote two short loops. The outer loop ran 3 times; each time, the inner loop ran 4 times.
Loops inside loops build anything with rows and columns: a game grid of enemies, the squares of a checkerboard, the pixels of an image, every seat in a theater. The outer loop counts one way, the inner loop the other.
Try it yourself
Change range(3) to range(5) for five rows. Then swap col and row in the star line and watch the grid tip on its side.
The common mistake
Using only one of the two counters. If you write star(screen, 100, 120 + row * 130, ...) and forget col, every star in a row lands in the same spot — you get a single column, not a grid. Both counters have to be in the star line.
What it unlocks
Grids build on for loops and range(), and give you the layouts behind games, art, and puzzles.