How to generate a rhombus pattern using stars in Python
Numerous patterns can be printed using Python, once we have a strong grip of the concepts involving loops. In this shot, we will use simple for loops to generate a rhombus pattern using stars.
A rhombus is a plane figure that consists of four sides that are identical in terms of magnitude. To create a rhombus in Python, we use two nested for loops inside an outer loop:
- An outer loop: To loop through the number of rows.
- Inner loops: One to print the trailing spaces and the other to print the pattern.
Code
Let’s look at the code snippet below.
# Number of rowsrows = 4# Loop through rowsfor i in range (1,rows + 1):# Trailing spacesfor j in range (1,rows - i + 1):print (end=" ")# Printing patternfor j in range (1,rows + 1):print ("*",end=" ")print()
Explanation
-
In line 2, we defined the number of rows (i.e., length of the rhombus).
-
In line 5, we created a
forloop to iterate through the number of rows. -
In Lines 8 and 9, we created an inner nested
forloop to account for the trailing spaces. The end statement in line 9 helps to stay on the same line. -
In lines 12 to 14, we created the second inner nested loop to print the patterns.
- The end statement helps to stay on the same line.
- The
print()statement is
used to move to the next line.