Nested loops, explained simply
A nested loop is a loop inside another loop. The inner loop runs all the way through every single time the outer loop goes round once.
Think of a grid: the outer loop picks a row, and the inner loop fills in every square in that row. Three rows of four squares means the inner line runs twelve times.
Nested loops are how programs draw patterns, fill game boards and check every pair of things against each other.
Example: A tiny mosaic
for row in range(3):
line = ""
for col in range(5):
line = line + "#"
print(line)Output
#####
#####
#####Try this
- Change the numbers to make a tall, thin rectangle.
- Use range(row + 1) for the inner loop and discover the triangle.
- Alternate two symbols to make a chequered pattern.
