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 Rowsrow = 8# Upper-Halffor 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-Halffor 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
forloop to print the upper half of the hourglass. -
In lines 6 and 7, we create a
forloop to create the spaced alignment. -
In lines 8 to 11, we create another
forloop to print the upper pattern.- We use
chto create alphabets from numbers by using the iterative value ofiand the concept of ASCII conversion. The starting value, 64 + (i=1), is used because the ASCII value ofAis 65. - The
endstatement is used to stay on the same line. - The
print()statement is used to move to the next line.
- We use
-
From lines 14 to 20, we create another
forloop to print the lower half of the hourglass. -
In lines 15 and 16, we create a
forloop to create the spaced alignment. -
From lines 17 to 20, we create another
forloop to print the lower pattern.