Related Tags

communitycreator
python

How to generate an hourglass pattern with numbers in Python

Vinisha Maheshwari

In this shot, we will learn how to generate an hourglass pattern using numbers in Python.

Different patterns can be generated in Python once you have a strong grip over loops. Here, we will use simple for loops to generate an hourglass pattern with numbers.

Description

We will use two for loops (one for the upper half and the other for the lower half), which will each contain two for loops within the outer loop.

Code

Let us take a look at the code snippet below.

# Number of Rows
row = 5

# 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(i, 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(i, end="")
print()

Run the code to see hourglass pattern

Explanation

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

• From lines 5 to 10, 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 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.
• From lines 13 to 18, we create another for loop to print the lower half of the hourglass.

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

• From lines 16 to 18, we create another for loop to print the lower pattern.

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

RELATED TAGS

communitycreator
python

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time