1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

Nested loops

A loop inside a loop: the inner loop runs completely for every single pass of the outer loop.

print normally ends with a new line. end="" swaps that for nothing, so the next print continues on the same line:

for row in range(2):
    for col in range(3):
        print("*", end="")
    print()        # finish the row
# ***
# ***

To print a list of text labels on one line, " ".join(labels) returns one string with a space between each pair of labels and none at the ends. For example, " ".join(["A1", "A2"]) gives "A1 A2".

See it run

for r in range(1, 3):
    for c in range(1, 4):
        print(r * c)

The inner loop runs completely for every single pass of the outer loop. Watch c restart.

Practice nested loops

Exercise 1

Print a grid of # that is 3 rows by 4 columns using two nested for loops.

Exercise 2

Use row_names and seats in the editor below. Print theatre seat labels with nested for loops: two rows named A and B, three seats each. Each row is one line: A1 A2 A3 then B1 B2 B3. Do not leave trailing spaces.

Exercise 3

Print a 4-row practice pyramid using nested for loops. Row 1 has one *, row 2 has two, up to four. No spaces or empty lines.

Exercise 4

Predict, then verify. Read this program before running it:

count = 0
for row in range(1, 4):
    for col in range(row):
        count += 1

At the moment row first becomes 3, what is count? Guess first. Then run it, press Step through your code, and press Next until the row box shows 3. Read count there and set prediction to that number.

The explanation and tasks are public. Running this lesson requires an account with course access.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest