Start free

GCSE · 7 exercises

Python nested loops

A loop inside a loop: for each turn of the outer loop, the inner one runs all the way through. Good for rows and columns.

print(..., end="") stays on the same line; an empty print() after the inner loop moves to the next row.

for row in range(1, 4):
    line = []
    for col in range(1, 4):
        line.append(str(row * col))
    print(" ".join(line))

Watch for: print(x, end=" ") leaves a space at the end of every line, and the tests see it. Build each line as a list and print " ".join(line): spaces only between.

Exercises

  1. Multiplication gridPrint an n by n multiplication grid.Intermediate
  2. PyramidPrint a pyramid of stars n rows high.Intermediate
  3. Number trianglePrint n rows: row i holds the numbers 1 to i separated by spaces.Intermediate
  4. Hollow squarePrint an n by n square of # with only the border filled; the inside is spaces.Intermediate
  5. DiamondPrint a diamond of stars: a pyramid of n rows, then the same pyramid upside downIntermediate
  6. CheckerboardPrint an n by n checkerboard of # and .Intermediate
  7. Pairs that add upCount the pairs of positions (i < j) whose numbers add up to a target.Intermediate
Start with “Multiplication grid”