In this shot, we will discuss how to generate a hollow diamond pattern using stars in Python. Numerous patterns can be printed using python, once we have a strong grip over the concepts involving loops. Here we will use simple for
loops to generate a hollow diamond pattern using stars.
To execute the same using Python programming, we will be using 2 outer for
loops and 4 nested loops to print the pattern:
Let’s look at the code snippet below.
# Number of rowsrow = 5# Upper part of hollow diamondfor i in range(1, row+1):for j in range(1,row-i+1):print(" ", end="")for j in range(1, 2*i):if j==1 or j==2*i-1:print("*", end="")else:print(" ", end="")print()# Lower part of hollow diamondfor i in range(row-1,0, -1):for j in range(1,row-i+1):print(" ", end="")for j in range(1, 2*i):if j==1 or j==2*i-1:print("*", end="")else:print(" ", end="")print()
In line 2, we take the input for the number of rows (i.e., the length of one side of the diamond).
From lines 5 to 13, we create a for
loop to generate the upper triangle.
In line 5, we create a for
loop to handle the number of rows.
In lines 6 and 7, we create a loop to handle the number of spaces.
In lines 8 to 13, we create a loop to print the patterns.
print()
statement is used to move to the next line.From lines 16 to 24, we create a for
loop to generate the lower triangle.
In line 16, we create a for
loop to handle the number of rows.
In lines 17 and 18, we create a loop to handle the number of spaces.
In lines 19 to 24, we create a loop to print the patterns.
print()
statement is used to move to the next line.