Related Tags

communitycreator
python

How to generate a rhombus pattern using numbers in Python

Vinisha Maheshwari

Numerous patterns can be printed using Python once we understand how to utilize loops. Here, we will use simple for loops to generate a rhombus pattern with numbers.

Description

A rhombus is a plane figure that consists of 4 sides that are identical in terms of magnitude. To execute the same using Python programming, we will use two nested for loops inside an outer loop:

• An outer loop: To loop through the number of rows.
• Two inner loops: One to print the trailing spaces and the other to print the pattern.

Code

Let us 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 (i,end="")
print()



Explanation

• In line 2, we took the input for the number of rows, i.e., the 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 line 12, we created the second inner nested loop to print the pattern using numbers.

• In line 13, we printed i, and i increases by the number of rows.

RELATED TAGS

communitycreator
python

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time