A diamond is a centred pyramid with an upside-down pyramid under it. The first loop prints the top half, and the second loop prints the bottom half in reverse order.
The program
python
n = int(input("Rows in the top half: ")) for i in range(1, n + 1): print(" " * (n - i) + "*" * (2 * i - 1)) for i in range(n - 1, 0, -1): print(" " * (n - i) + "*" * (2 * i - 1))
Typed in this example: 4. Press Run to type your own.
output
Rows in the top half: 4 * *** ***** ******* ***** *** *
How it works
- Row
ihas2 * i - 1stars (1, 3, 5, 7) andn - ispaces in front. range(n - 1, 0, -1)counts down from 3 to 1. It starts atn - 1so that the widest row is printed only once.- The spaces go only in front of the stars, so no line ends with a space.
A hollow diamond
For an outline, each row prints a star, then spaces, then a second star. The top and bottom rows have only one star:
python
n = 4 for i in list(range(1, n + 1)) + list(range(n - 1, 0, -1)): width = 2 * i - 1 if width == 1: row = "*" else: row = "*" + " " * (width - 2) + "*" print(" " * (n - i) + row)
output
* * * * * * * * * * * *
list(range(1, 5)) + list(range(3, 0, -1))gives[1, 2, 3, 4, 3, 2, 1], so a single loop prints both halves.width - 2is the number of spaces between the two stars on each row.
For a single pyramid, see the star triangle pattern.