a shot of dev knowledge

RELATED TAGS

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

  • 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 end statement helps to stay on the same line.
    • The print() statement is used to move to the next line.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring