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.
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.
Let us take a look at the code snippet below.
# Number of Rowsrow = 4# Upper-Halffor 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-Halffor i in range(2, row+1):for j in range(row-i):print(" ", end="")for j in range(1, 2*i):print("*", end="")print()
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.
end
statement is used to stay on the same line.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.
end
statement helps stay on the same line.print()
statement is used to move to the next line.