Python Practice › Loop Programs › Program 42
Number diamond pattern
Write a Python program to print rows of numbers that grow from 1 to 5 numbers (1 to 15) and then shrink, counting back down (14 to 5).
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 14 13 12 11 10 9 8 7 6 5
Approach
- Upper half: keep a counter that increases across rows of length 1 to 5.
- Lower half: continue from 14 counting down, rows of length 4 to 1.
Solution
n = 5num = 1for row in range(1, n + 1): print(" ".join(f"{num + i:2}" for i in range(row))) num += rownum -= 2 # last printed was 15, continue from 14for row in range(n - 1, 0, -1): print(" ".join(f"{num - i:2}" for i in range(row))) num -= rowOutput
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 14 13 12 11 10 9 8 7 6 5
Line by line
Line 4
Each row prints row consecutive numbers starting at num.
Line 5
The next row starts after the numbers just printed.
Line 6
After the top half num is 16, so subtracting 2 gives 14.
Lines 7-9
The lower half counts down, row lengths 4, 3, 2, 1.
Learn the concept
New to this topic? Read the lesson, then come back.