How to generate an hourglass pattern with numbers in Python
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 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):print(i, 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):print(i, end="")print()
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
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 10, we create another
forloop to print the upper pattern.- The
endstatement is used to stay on the same line. - The
print()statement is used to move to the next line.
- The
-
From lines 13 to 18, we create another
forloop to print the lower half of the hourglass. -
In lines 14 and 15, we create a
forloop to create the spaced alignment. -
From lines 16 to 18, we create another
forloop to print the lower pattern.- The
endstatement helps to stay on the same line. - The
print()statement is used to move to the next line.
- The