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.
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.
Let us take a look at the code snippet below.
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.
end
statement is used to stay on the same line.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.
end
statement helps to stay on the same line.print()
statement is used to move to the next line.