How to generate a hollow rhombus pattern using stars in Python

In this shot, we will discuss how to generate a hollow rhombus pattern with stars in Python. Numerous patterns can be printed with Python once you have a strong grip on concepts involving loops. Here, we will use simple for loops to generate a hollow rhombus pattern with stars.

Description

A rhombus is a plane figure that consists of 4 sides that are identical in terms of magnitude. To print a rhombus with Python programming, we will use an outer for loop coupled with nested loops.

Code

Let’s look at the code snippet.

# 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=" ")
# Print pattern for each solid rows
if i == 1 or i == rows:
for j in range (1, rows + 1):
print ("*",end=" ")
# Print pattern for hollow rows
else:
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., the length of the rhombus).

  • In line 5, we create a for loop to iterate through the number of rows.

  • In lines 8 and 9, we create 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 line 12, we give the conditions for the solid rows.

  • In lines 13 and 14, we print the pattern on the solid rows.

  • From lines 17 to 23, we create conditions for hollow rows and print the pattern on the hollow rows.

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

Free Resources