How to generate a hollow hourglass pattern with numbers in Python

We can generate different patterns in Python once we have a strong grip over the concepts involving loops.

In this shot, we will use for loops and numbers to generate a hollow hourglass pattern.

Description

We will use 2 for loops (one for the upper half and the other for the lower half of the hollow hourglass) that contain 2 nested for loops to generate an hourglass pattern.

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(i, 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==1 or i==row or j==1 or j==2*i-1:
print(i, end=" ")
else:
print(" ", end=" ")
print()

Explanation

  • In line 2, we set the number of rows to 5 (i.e. the length of the hourglass).

  • In lines 5-13, we use the first outer for loop to print the upper half of the hourglass.

  • In lines 6-7, we use the for loop to create the spaced-alignment.

  • In lines 8-13, we use another for loop to print the upper pattern.

    • We print i, as i decreases with every increase in the row number in the upper half of the hourglass.
    • end = "" in the print statement is used to stay on the same line.
    • The print() statement is used to move to the next line.
  • In lines 16-24, we use the second outer for loop to print the lower half of the hourglass.

  • In lines 17-18, we use the for loop to create the spaced-alignment.

  • In lines 19-24, we use another for loop to print the lower pattern.

    • We print i, as i increases with every increase in the row number in the lower half of the hourglass.
    • end = "" in the print statement is used to stay on the same line.
    • The print() statement is used to move to the next line.