Loops · Lesson 15 of 27
Nested loops and patterns
A loop inside another loop is a nested loop. For every round of the outer loop, the inner loop runs completely.
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end=" ")
print() # new line after each rowOutput:
1 2 3 2 4 6 3 6 9
Pattern questions (stars, number triangles) are very common in coding tests. The trick: the outer loop is the row, the inner loop prints what goes in that row.
for i in range(1, 4):
print("*" * i)Your task
Read n and print a number triangle with n rows. For n = 4:
1 1 2 1 2 3 1 2 3 4