In this shot, we will learn how to generate a hollow hourglass pattern using stars in Python.
Once you have a strong grip over the concepts involving loops, you can generate different patterns in Python. Here, we will use for
loops to generate a hollow hourglass pattern with stars.
To execute this pattern in Python, we will use two for
loops (one for the upper half and the other for the lower half) that contain two nested for
loops.
Let’s look at the code snippet below.
# 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):if i==1 or i==row or j==1 or j==2*i-1:print("*", 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):if i==row or j==1 or j==2*i-1:print("*", end=" ")else:print(" ", end=" ")print()
for
loop to print the upper half of the hourglass.for
loop to create the spaced alignment.for
loop to print the upper pattern.
i==row
⇒ prints the upper edge of the hourglassj==1
⇒ prints the upper-left side of the hourglassj==2*i-1
⇒ prints the upper-right side of the hourglassi==1
⇒ prints the middle pointend
statement is used to stay on the same lineprint()
statement is used to move to the next linefor
loop to print the lower half of the hourglass.for
loop to create the spaced alignment.for
loop to print the lower pattern.
i==row
⇒ prints the base of the hourglassj==1
⇒ prints the lower-left side of the hourglassj==2*i-1
⇒ prints the lower-right side of the hourglassend
statement helps to stay on the same lineprint()
statement is used to move to the next line