How to generate a hollow rhombus pattern in Python
Numerous patterns can be printed using Python, once we have a strong grip over the concepts involving loops. Here, we will be using simple for loops to generate a hollow rhombus pattern.
Description
A rhombus is a plane figure consisting of four sides that are identical in terms of magnitude. To execute this figure using Python programming, we will be using an outer for loop assisted with some nested loops.
Code
Let’s look at the code snippet.
# Number of rowsrows = 4# Loop through rowsfor i in range (1,rows + 1):# Trailing spacesfor j in range (1, rows - i + 1):print (end=" ")# Print pattern for each solid rowsif i == 1 or i == rows:for j in range (1, rows + 1):print ('*',end=" ")# Print pattern for hollow rowselse:for j in range (1,rows+1):if (j == 1 or j == rows):print ('*',end=" ")else:print (end=" ")print()
Explanation
-
In line 2, we take the input for the number of rows (i.e., length of the rhombus).
-
In line 5, we create a
forloop to iterate through the number of rows. -
In lines 8 and 9, we create an inner nested
forloop to account for the trailing spaces. The end statement in line 9 helps to stay on the same line. -
In line 12, we give the conditions for the solid rows.
-
In lines 13 and 14, we print the pattern on the solid rows.
-
In lines 19 and 20, we print
*at the start and end of each row. -
In line 23, we print a double space for the hollow rows.
- The
endstatement helps to stay on the same line. - The
print()statement is used to move to the next line.
- The