How to generate an hourglass pattern with stars in Python

Different patterns can be generated in Python once you have a firm grip over the concepts involving loops. In this shot, we will use simple for loops to generate an hourglass pattern with stars.

Description

To generate an hourglass pattern, we will use two for loops (one for the upper half and the other for the lower half) that each contains two nested for loops within the outer loop.

Example

Let us take a look at the code snippet below.

# Number of Rows
row = 4
# Upper-Half
for i in range(row, 0, -1):
for j in range(row-i):
print(" ", end="")
for j in range(1, 2*i):
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):
print("*", end="")
print()

Code explanation

  • Line 2: We take the input for the number of rows (i.e. the length of the hourglass).

  • Lines 5 - 10: We create a for loop to print the upper half of the hourglass.

  • Lines 6 and 7: We create a for loop to create the spaced-alignment.

  • Lines 8 - 10: We create another for loop to print the upper pattern.

    • The end statement is used to stay on the same line.
    • The print() statement is used to move to the next line.
  • Lines 13 - 18: We create another for loop to print the lower half of the hourglass.

  • Lines 14 and 15: We create a for loop to create the spaced-alignment.

  • Lines 16 - 18: We create another for loop to print the lower pattern.

    • The end statement helps stay on the same line.
    • The print() statement is used to move to the next line.

Free Resources