Nested Loops and Patterns

45 min read Loops in Depth

This is a free course. Log in to run the code exercises and track your progress.

Nested Loops and Patterns

A loop inside another loop is a nested loop. For every single pass of the outer loop, the inner loop runs completely. Patterns are the classic use: the outer loop chooses the row and the inner loop prints what goes in that row.

n = 4
for row in range(1, n + 1):
    for col in range(1, row + 1):
        print(col, end=" ")
    print()          # move to the next line

This prints:

1
1 2
1 2 3
1 2 3 4

Row row has row numbers, so the inner range ends at row + 1. For a star triangle, string repetition is even shorter: print("*" * row) prints row stars.

Python exercise

Read n and print a right-angled triangle of * with n rows: row 1 has one star, row n has n stars.

n = int(input())
for row in range(1, n + 1):
    print("*")  # print row stars

Log in to edit and run this code.