Nested loops and patterns
Loops inside loops. Draw shapes, grids and multiplication squares.
Code runs right here in your browser. Nothing to install.
Learn it
The inner loop runs completely for every turn of the outer loop.
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.
for row in range(1, 4): for col in range(1, 4): print(row * col, end="\t") print()
Try it yourself
+10 XPPrint 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.
Capture the flag
+10 XPAn 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.
Hollow square
+20 XPAsk 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.