Nested loops and patterns
Part of the free LogicWiz Python course, Module 2: Decisions and loops. The examples and practice run in the app.
Almost every CBSE paper has a pattern question: print a triangle of stars or numbers. Once you see rows and columns, every pattern is the same two loops.
You'll learn to
- See that the inner loop runs fully for each round of the outer loop
- Print star, number and alphabet patterns
- Work out spaces and stars per row with a small table
Learn
A loop inside a loop
for row in range(1, 4):
for col in range(1, 3):
print(row, col)
For each row, the inner loop runs through all its columns. 3 rows × 2 columns = 6 lines. The outer loop is the hour hand, the inner loop is the minute hand.
Rows and columns
For a pattern:
- The outer loop counts the rows.
- The inner loop prints what goes in that row.
print(..., end="")keeps printing on the same line.- A bare
print()after the inner loop ends the row.
The key question for every pattern: in row i, how many of what?
A right triangle of stars
n = 4
for i in range(1, n + 1):
for j in range(i):
print("*", end="")
print()
for i in range(1, n + 1):
print("*" * i)
Row i has i stars. The second loop does the same with string repetition: in Python, "*" * i is a shortcut for the inner loop. Examiners often want to see the nested version, so know both.
Number patterns
n = 4
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end=" ")
print()
for i in range(1, n + 1):
for j in range(i):
print(i, end=" ")
print()
Print j (the column) and every row counts 1, 2, 3… Print i (the row) and every row repeats its own number. Which name you print decides the pattern.
Alphabet patterns
print(ord("A"), chr(66))
n = 4
for i in range(n):
for j in range(i + 1):
print(chr(65 + j), end=" ")
print()
Every character has a number: ord("A") is 65, and chr(66) is "B". So chr(65 + j) gives A, B, C, … as j goes 0, 1, 2, …
A pyramid needs spaces
n = 4
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
For n = 4: row 1 has 3 spaces and 1 star, row 2 has 2 spaces and 3 stars, and so on. Spaces go down by 1 and stars go up by 2.
Stuck on a pattern? Make a table for n = 4 with columns row, spaces, stars. Fill it in by looking at the picture, then find the formula: spaces = n - i, stars = 2 * i - 1. The code writes itself.
If every star lands on its own line, your print() is inside the inner loop. It must line up with the inner for, not sit inside it.
Board papers ask you to write a pattern program for n rows (usually 3-5 marks) or to give the output of a nested loop. Trace a nested loop row by row: finish the whole inner loop before moving to the next outer value.
In one line
The outer loop counts rows, the inner loop fills a row; end each row with print(), and work out spaces and stars per row with a small table.