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.

Error: Code Widget Crashed, Please Contact Support

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.

Free Resources