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.
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.
Let’s look at the code for this:
# Number of Rowsrow = 5# 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)if i==1 or i==row or j==1 or j==2*i-1:print(ch, end="")else:print(" ", 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)if i==1 or i==row or j==1 or j==2*i-1:print(ch, end="")else:print(" ", end="")print()
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.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.print()
statement helps us move on to the next line.