PythonMastery

Diamond pattern in Python

Print a diamond of stars with two for loops, one for the top half and one for the bottom half, then a hollow diamond outline.

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

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
   *
  * *
 *   *
*     *
 *   *
  * *
   *

For a single pyramid, see the star triangle pattern.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Working with Strings