How to generate hourglass pattern using alphabets in Python

This shot will explain and demonstrate how we can generate a hollow hourglass pattern, using alphabets in Python.

We can generate different patterns using Python, once we have a strong grip over the Python concepts that involve loops. Here, we will use simple for loops and alphabets to generate an hourglass pattern.

Description

To execute an hourglass, using Python programming, we will use 2 for loops —one for the upper half and the other for the lower half. Each for loop will contain 2 nested for loops within the outer loop.

Code

Let’s look at the code for this:

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

Code explanation

  • In line 2, we have the input for the number of rows, that is, the length of the hourglass.

  • From lines 5 to 14, we create a for loop to print the upper half of the hourglass.

  • In lines 6 and 7, we make a for loop to create the spaced alignment.

  • In lines 8 to 14, we create another loop to print the upper pattern.

    • ch is used to create alphabets from numbers. It uses the iterative value of i and the concept of ASCII conversion. The starting value 64 + (i=1) is used because the ASCII value of A is 65.
    • 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 of the hourglass
    • The end statement is used for us to stay on the same line.
    • The print() statement is used for us to move on to the next line.
  • From lines 17 to 26, we create another for loop to print the lower half of the hourglass.

  • In lines 18 and 19, we make a for loop to create the spaced alignment.

  • From lines 20 to 26, we create another for loop to print the lower pattern.

    • ch is used to create alphabets from numbers. It uses the iterative value of i and the concept of ASCII conversion. The starting value 64 + (i=1) is used, because the ASCII value of A is 65.
    • 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
    • i==1 ⇒ prints the middle point of the hourglass
    • The end statement helps us stay on the same line.
    • The print() statement helps us move on to the next line.

Free Resources