Course 4.1Lesson 4 of 5
A loop can sit inside another loop. The inner loop runs completely, from start to end, in every round of the outer loop. So an outer loop of 3 rounds and an inner loop of 4 rounds run the body 12 times. Nested loops make tables, grids and patterns. Use print with end to stay on a line, and a plain print after the inner loop to start a new line. Use different names for the two loop variables, and a trace table to follow them.
Try the code and the simulations beside the lesson.
After this lesson you can
Think about a clock. The minute hand goes around completely for every one step of the hour hand. A nested loop works like that: the outer loop is the slow hand, and the inner loop is the fast hand.
a = 1. The inner loop runs all of its rounds: b = 1, b = 2, b = 3.a = 2. The inner loop starts again from the beginning, and runs all of its rounds again.The outer loop has 2 rounds, the inner loop has 3. So the body runs 2 times 3, which is 6 times. This is the rule: the number of times is the product of the rounds.
Nested loops are perfect for tables and grids. The outer loop makes the rows, and the inner loop makes the columns.
If you forget that last print(), all the numbers stand in one long line. If you put it inside the inner loop, every number gets its own line. The indent decides.
The plain print() sits after the inner loop, so it runs once for each row and starts the next line.
Write one row for each time the body runs, with a column for each loop variable.
row | col | printed |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 2 | 2 |
| 1 | 3 | 3 |
| 1 | 4 | 4 |
| 2 | 1 | 2 |
The row changes slowly, and the col changes fast. The table continues in the same way, 12 rows in all.
Patterns are a good way to practise nested loops. A pattern is made of rows, and each row is made of characters. Often the inner loop is not needed, because "*" * n makes a whole row at once. But when each character depends on both the row and the column, you need two loops.
How many stars are in row i of a triangle? i. And how many spaces come before the stars of a pyramid? The height minus i. Find these relations on paper before you write the code.
row and col, or i and j.print() that starts a new line.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
end="" keeps the output on the same line. A plain print() after the inner loop starts a new line.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
for a in range(5): for b in range(4):?print() do?print() for a new line go?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.