TwiddleLab / Code / Build with Python
Loops Inside Loops
What you will learn
- A nested loop is a loop inside a loop: the inner loop runs all the way through for every turn of the outer one.
- 3 rows of 4 is 3 x 4 = 12 runs of the inner body.
- The inner range can use the outer variable: range(r + 1) makes a triangle.
- (r + c) % 2 == 0 picks every other cell: a chessboard.
How the lesson goes
Three lines of code paint a block of cells. How many cells?
Place your pin on the scale.
Run it. Watch the two counters.
c is the inner wheel, r the outer one. One painted cell per step.
Now the inner loop depends on r. Which cell comes next?
Tap the cell you think gets painted next.
Nested loops.
A nested loop is a loop in the body of another loop. Indentation shows which is inside.
For every value of the outer variable, the inner loop runs all the way through.
Total runs of the inner body: outer count times inner count, when the inner range doesn't change. When it uses the outer variable, add up row by row.
Fill the dashed frame exactly.
The sliders change the numbers in the two ranges.
Pattern painter: match four targets.
Pick what the inner loop runs over and when to paint. Fewest paints wins.
Make your own pattern.
Mix the tiles until you like what you see. Keep it with Check.
10 players. Every pair shakes hands once. How many handshakes?
Two programs try to count. Run both, then tap the one that counts each pair once.
How many times does print run?
Careful: the inner range uses i.
Your pattern, as wallpaper.
Drag n up. Same code, bigger grid.
Previous lesson: And, Or, Not · Next lesson: Dictionaries: Labels, Not Numbers · Part of the course: Build with Python
Lessons are interactive and need JavaScript. Turn it on to play them.