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:
Let’s look at the code snippet below.
# Number of rows rows = 4 # Loop through rows for i in range (1,rows + 1): # Trailing spaces for j in range (1,rows - i + 1): print (end=" ") # Printing pattern for j in range (1,rows + 1): print ("*",end=" ") print()
In line 2, we defined the number of rows (i.e., length of the rhombus).
In line 5, we created a for
loop to iterate through the number of rows.
In Lines 8 and 9, we created an inner nested for
loop 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.
print()
statement isRELATED TAGS
CONTRIBUTOR
View all Courses