Python Code Example: diamond pattern

This code generates a pattern that looks like a diamond made of asterisks (*). It does this by creating an upper pyramid (the top half of the diamond) and a lower pyramid (the bottom half of the diamond).

Code Example

rows = 8

# upper pyramid
for i in range(1, rows):
    for j in range(1, rows - i):
        print(' ', end='')
    for j in range(0, 2 * i - 1):
        print('*', end='')
    print()

# lower pyramid
for i in range(rows - 2, 0, -1):
    for j in range(1, rows - i):
        print(' ', end='')
    for j in range(1, 2 * i):
        print('*', end='')
    print()

Output

      *
     ***
    *****
   *******
  *********
 ***********
*************
 ***********
  *********
   *******
    *****
     ***
      *

Code Explanation

Initial Setup

rows = 8

This line sets the number of rows for the pyramids. In this case, there are 8 rows.

Upper Pyramid

for i in range(1, rows):
    for j in range(1, rows - i):
        print(' ', end='')
    for j in range(0, 2 * i - 1):
        print('*', end='')
    print()

This block of code creates the upper pyramid. Let’s go through it step-by-step:

  1. Outer Loop:for i in range(1, rows)
    • This loop runs from 1 to rows - 1 (i.e., 1 to 7). Each iteration represents a row in the upper pyramid.
  2. First Inner Loop:for j in range(1, rows - i)
    • This loop prints spaces before the asterisks to center them. The number of spaces decreases as i increases.
  3. Second Inner Loop:for j in range(0, 2 * i - 1)
    • This loop prints the asterisks. The number of asterisks in each row is (2 * i - 1). It increases as i increases.
  4. print() Statement:print()
    • This moves the cursor to the next line after printing all the spaces and asterisks for the current row.

Lower Pyramid

for i in range(rows - 2, 0, -1):
    for j in range(1, rows - i):
        print(' ', end='')
    for j in range(1, 2 * i):
        print('*', end='')
    print()

This block of code creates the lower pyramid. Here’s the breakdown:

  1. Outer Loop:for i in range(rows - 2, 0, -1)
    • This loop runs from rows - 2 to 1 (i.e., 6 to 1). Each iteration represents a row in the lower pyramid.
  2. First Inner Loop:for j in range(1, rows - i)
    • This loop prints spaces before the asterisks to center them. The number of spaces decreases as i decreases.
  3. Second Inner Loop:for j in range(1, 2 * i)
    • This loop prints the asterisks. The number of asterisks in each row is 2 * i - 1 in the upper pyramid and 2 * i in the lower pyramid. The number decreases as i decreases.
  4. print() Statement:print()
    • This moves the cursor to the next line after printing all the spaces and asterisks for the current row.