Nested Loops and Pattern Programs
This is a free course. Log in to run the code exercises and track your progress.
Nested Loops and Pattern Programs
In a nested loop the inner loop runs completely for each pass of the outer loop. Pattern programs use the outer loop for rows and the inner loop for the items in a row.
n = 4
for i in range(n, 0, -1):
for j in range(1, i + 1):
print(j, end="")
print()
Output:
1234
123
12
1
To work out the inner loop of any pattern, write down for each row number i what is printed, then find the rule. A pyramid also needs leading spaces: row i of an n-row pyramid starts with n - i spaces.
for i in range(1, 4):
print(" " * (3 - i) + "*" * (2 * i - 1))
Read n and print the pattern where row i (1 to n) shows the numbers 1 to i with no spaces.
n = int(input())
for i in range(1, n + 1):
for j in range(1, n + 1): # how far should j go in row i?
print(j, end="")
print()Log in to edit and run this code.