Browser lab15 min+60 XP

Nested loops and patterns

Loops inside loops. Draw shapes, grids and multiplication squares.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

The inner loop runs completely for every turn of the outer loop.

Key words
1234246836912row 1row 2row 3col 1col 2col 3col 4inner loop: acrossouter loop: down
A times table: the outer loop picks the row, the inner loop fills it.

You can put a loop inside another loop. The inner loop runs completely for every single turn of the outer loop. With an outer loop of 3 and an inner loop of 4, the inner block runs 3 x 4 = 12 times.

Nested loops are perfect for rows and columns: the outer loop picks the row and the inner loop prints across it. Use end="" to stay on the same line, then an empty print() to move to the next row.

Real life linkA screen is drawn row by row, and each row pixel by pixel. That is a loop inside a loop, exactly like the patterns in this room.
Example code
for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end="\t")
    print()
TASK 2

Try it yourself

+10 XP

Print a right-angled triangle of * with 5 rows: 1 star on row 1, 2 stars on row 2, up to 5 stars. Use nested loops (no "*" * n shortcut).

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

An outer loop runs 3 times and the inner loop runs 4 times each turn. How many times does the inner block run in total?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Hollow square

+20 XP

Ask for a size. Print a hollow square of #: the first and last rows are full, and the middle rows have # only at the start and end, with spaces between. For size 4 the output is:
####
# #
# #
####

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.