Editor

Python Program to Print an Hourglass Pattern

Beginner · Patterns

An hourglass pattern looks like a sand timer: an upside-down pyramid on top of a normal pyramid, meeting at a single star in the middle. With 5 rows in each half, the rows have 9, 7, 5, 3 and 1 stars, then 3, 5, 7 and 9 again.

Program

hourglass_pattern.py
rows = 5 # rows in each half; or: rows = int(input("Enter the number of rows: "))
# Top half: shrink from 9 stars down to 1
for i in range(rows, 0, -1):
print(" " * (rows - i) + "*" * (2 * i - 1))
# Bottom half: grow from 3 stars back up to 9
for i in range(2, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))
Output
*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********

How it works

  1. Both halves use the pyramid rule: row i has rows - i spaces and then 2 * i - 1 stars.
  2. The top half counts i down from 5 to 1, which draws an inverted pyramid ending in the single star at the waist.
  3. The bottom half counts i up from 2 to 5, starting at 2 rather than 1 so the middle star is not printed twice.
  4. " " * n and "*" * n build each part of the row by repeating a character.

Other ways to write it

Hourglass with spaces between the stars

Hourglass with spaces between the stars
rows = 5
for i in range(rows, 0, -1):
print(" " * (rows - i) + "* " * i)
for i in range(2, rows + 1):
print(" " * (rows - i) + "* " * i)
Output
* * * * * 
 * * * * 
  * * * 
   * * 
    * 
   * * 
  * * * 
 * * * * 
* * * * *

With "* " repeated i times, the rows have 5, 4, 3, 2 and 1 stars and then grow again, and one space of indent per row keeps them centred.

One loop using abs()

One loop using abs()
rows = 5
for k in range(-(rows - 1), rows): # -4 to 4
i = abs(k) + 1 # 5, 4, 3, 2, 1, 2, 3, 4, 5
print(" " * (rows - i) + "*" * (2 * i - 1))
Output
*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********

abs(k) + 1 is large at both ends of the loop and 1 in the middle, which is exactly the shape of an hourglass.

Try it yourself

Make the hourglass hollow, so each row prints only its first and last star.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises