Python Code Example: hourglass pattern

This code example is a Python script that prints a diamond shape composed of asterisks (*).

Code Example

n = 8

for i in range(1, n):
    for j in range(1, i):
        print(' ', end='')
    for k in range(i, n):
        print("* ", end='')
    print()

for i in range(n - 1, 0, -1):
    for j in range(1, i):
        print(' ', end='')
    for k in range(i, n):
        print("* ", end='')
    print()

Output

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

Code Explanation

Initialize the variable n

n = 8

This sets the height of the diamond. The diamond will have n-1 rows in the upper part and n-1 rows in the lower part, for a total height of 2*(n-1).

First part of the diamond (upper part)

for i in range(1, n):
    for j in range(1, i):
        print(' ', end='')
    for k in range(i, n):
        print("* ", end='')
    print()
  • for i in range(1, n): iterates i from 1 to n-1.
  • for j in range(1, i): prints spaces before the asterisks, increasing the number of spaces as i increases.
  • for k in range(i, n): prints the asterisks. The number of asterisks decreases as i increases.
  • print() moves to the next line after each row.

The upper part of the diamond is generated by decreasing the number of asterisks and increasing the number of leading spaces with each row.

Second part of the diamond (lower part)

for i in range(n - 1, 0, -1):
    for j in range(1, i):
        print(' ', end='')
    for k in range(i, n):
        print("* ", end='')
    print()
  • for i in range(n - 1, 0, -1): iterates i from n-1 down to 1.
  • for j in range(1, i): prints spaces before the asterisks, decreasing the number of spaces as i decreases.
  • for k in range(i, n): prints the asterisks. The number of asterisks increases as i decreases.
  • print() moves to the next line after each row.

The lower part of the diamond is generated by increasing the number of asterisks and decreasing the number of leading spaces with each row.

Output Analysis

  • The upper part of the diamond starts with n-1 asterisks and reduces down to 1 asterisk, shifting right by one space in each row.
  • The lower part of the diamond starts with 1 asterisk and increases up to n-1 asterisks, shifting left by one space in each row.