Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.7 — Nested Loops and Patterns
Python · Example 1 of 2

A table and a triangle

Change both ranges to range(1, 6) for a 5 by 5 table. Then try f"{row * col:4}" to widen the columns.

A loop inside a loop runs the inner loop completely for every pass of the outer loop, so the total work is rows times columns. Nested loops draw grids and tables, and leaving both loops at once needs a flag, a for/else, or (later) a function.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print a rectangle of # 3 rows high and 5 columns wide using two loops.

02

Print every pair (i, j) with i and j from 0 to 1, as 0 0, 0 1, 1 0, 1 1, one per line.

03

Count how many steps a loop of 5 outer and 4 inner passes makes and print Steps: 20.

04

In numbers = [1, 4, 6, 9], find the first pair a < b (checking a from the list in order, then b in order) whose sum is 10 and print Found: (1, 9). Stop both loops.

Explain it without notes

01

How many times does the innermost statement run in two nested loops of sizes n and m?

02

How do you print a grid with each row on its own line?

03

How can you exit two nested loops at once?

04

Why can reusing the same loop variable in nested loops cause bugs?

A table and a triangle
Sign in to run this example in your browser.

Expected output

  1  2  3
  2  4  6
  3  6  9
*
**
***
****