How to generate an hourglass pattern with alphabets in Python

Introduction

In this shot, we will discuss how to generate a solid hourglass pattern using alphabets in Python.

Different patterns can be generated in Python once you have a strong grip on loops. We will use simple for loops to generate an hourglass pattern using alphabets.

Description

To execute an hourglass with Python programming, we will use 2 for loops (one for the upper half and the other for the lower half) that each contains 2 nested for loops within the outer loop.

Code

Let’s have a look at the code.

# Number of Rows
row = 8
# 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)
print(ch, 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)
print(ch, end="")
print()

Explanation

  • In line 2, we take the input for the number of rows (i.e. the length of the hour-glass).

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

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

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

    • We use ch to create alphabets from numbers by using 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.
    • The end statement is used to stay on the same line.
    • The print() statement is used to move to the next line.
  • From lines 14 to 20, we create another for loop to print the lower half of the hourglass.

  • In lines 15 and 16, we create a for loop to create the spaced alignment.

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

Free Resources