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 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()

Explanation

  • 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.

    • The end statement helps to stay on the same line.
    • The print() statement is
      used to move to the next line.

Free Resources