How to generate a hollow hourglass pattern using stars in Python

Overview

In this shot, we will learn how to generate a hollow hourglass pattern using stars in Python.

Once you have a strong grip over the concepts involving loops, you can generate different patterns in Python. Here, we will use for loops to generate a hollow hourglass pattern with stars.

Description

To execute this pattern in Python, we will use two for loops (one for the upper half and the other for the lower half) that contain two nested for loops.

Code

Let’s look at the code snippet below.

# Number of Rows
row = 5
# Upper-Half
for i in range(row, 0, -1):
for j in range(row-i):
print(" ", end=" ")
for j in range(1, 2*i):
if i==1 or i==row or j==1 or j==2*i-1:
print("*", end=" ")
else:
print(" ", end=" ")
print()
# Lower-Half
for i in range(2, row+1):
for j in range(row-i):
print(" ", end=" ")
for j in range(1, 2*i):
if i==row or j==1 or j==2*i-1:
print("*", end=" ")
else:
print(" ", end=" ")
print()

Explanation

  • Line 2: We define the number of rows (i.e. the length of the hourglass).
  • Lines 5 to 13: We create a for loop to print the upper half of the hourglass.
  • Lines 6 and 7: We create a for loop to create the spaced alignment.
  • Lines 8 to 12: We create another for loop to print the upper pattern.
    • i==row ⇒ prints the upper edge of the hourglass
    • j==1 ⇒ prints the upper-left side of the hourglass
    • j==2*i-1 ⇒ prints the upper-right side of the hourglass
    • i==1 ⇒ prints the middle point
    • The end statement is used to stay on the same line
    • The print() statement is used to move to the next line
  • Lines 16 to 24: We create another for loop to print the lower half of the hourglass.
  • Lines 17 and 18: We create a for loop to create the spaced alignment.
  • Lines 19 to 23: We create another for loop to print the lower pattern.
    • i==row ⇒ prints the base of the hourglass
    • j==1 ⇒ prints the lower-left side of the hourglass
    • j==2*i-1 ⇒ prints the lower-right side of the hourglass
    • The end statement helps to stay on the same line
    • The print() statement is used to move to the next line

Free Resources