Python Program to Print a Diamond Pattern
Beginner Patterns
Prints a diamond of stars: the rows of a pyramid going down to the widest one, then the same rows again in reverse.
A diamond is a pyramid with an upside-down copy of itself underneath. With 5 rows to the middle, the top half has 1, 3, 5, 7 and 9 stars and the bottom half 7, 5, 3 and 1. The widest row is printed only once, so the diamond is 9 lines tall. Every line is worked out the same way as a pyramid's row, from its row number.
Program
def diamond(n):
"""Print a diamond of stars, 2 * n - 1 rows tall."""
# Rows 1 to n of a pyramid, then rows n - 1 back down to 1
rows = list(range(1, n + 1)) + list(range(n - 1, 0, -1))
for row in rows:
spaces = n - row
stars = 2 * row - 1
print(" " * spaces + "*" * stars)
diamond(5)
Open in the editor Download diamond.py
Output
*
***
*****
*******
*********
*******
*****
***
*
How it works
Step through the program line by line: each step below shows up as its line runs.
-
rowslists which pyramid row each line of the diamond copies: 1 up ton, thenn - 1back down to 1.range(n - 1, 0, -1)counts backwards, as its third number, the step, is -1, and it stops before 0 (for loops). Forn = 5,rowsis[1, 2, 3, 4, 5, 4, 3, 2, 1]. - The loop prints one line for each number in
rows. - As in a pyramid, row
rowhasn - rowspaces in front and2 * row - 1stars: the further down the pyramid, the fewer spaces and the more stars. - The spaces and then the stars make one string, printed as the line.
- The program prints a diamond 5 rows to the middle, 9 lines in all.
For n = 5:
| Line printed | row | Spaces: n - row |
Stars: 2 * row - 1 |
|---|---|---|---|
| 1 | 1 | 4 | 1 |
| 2 | 2 | 3 | 3 |
| 3 | 3 | 2 | 5 |
| 4 | 4 | 1 | 7 |
| 5 | 5 | 0 | 9 |
| 6 | 4 | 1 | 7 |
| 7 | 3 | 2 | 5 |
| 8 | 2 | 3 | 3 |
| 9 | 1 | 4 | 1 |
The middle star of every line lands in the 5th column, so the two halves line up.
Other ways to write it
With two loops
The version most courses show: one loop prints the top half, and a second, counting down, the bottom half.
def diamond(n):
for row in range(1, n + 1):
print(" " * (n - row) + "*" * (2 * row - 1))
for row in range(n - 1, 0, -1):
print(" " * (n - row) + "*" * (2 * row - 1))
diamond(3)With abs()
One loop can count i from 1 - n to n - 1. abs(i) drops the minus sign, so n - abs(i) goes up to n and back
down: 1, 2, 3, 2, 1 for n = 3.
def diamond(n):
for i in range(1 - n, n):
row = n - abs(i)
print(" " * (n - row) + "*" * (2 * row - 1))
diamond(3)Try it yourself
- Print
diamond(3)anddiamond(7). A diamondnrows to the middle is2 * n - 1lines tall: 13 for 7. - Swap the two halves of
rowsto make an hourglass:list(range(n, 0, -1)) + list(range(2, n + 1)). - Space the stars out: print
n - rowspaces, then"* " * row. - Make it hollow, with a star only at each end of a line: a row wider than one star prints
"*" + " " * (stars - 2) + "*".