How to generate a diamond pattern using numbers in Python

In this shot, we will discuss how to generate a diamond pattern using numbers in Python.

Numerous patterns can be printed using Python once we have a strong grasp of concepts involving loops. Here, we will be using simple for loops to generate a diamond pattern using numbers.

Description

To execute this using Python programming, we will be using two outer for loops, one for the upper triangle and the other for the lower triangle, and four nested loops to print the pattern:

  • Outer loops: One is used for the upper triangle while the other is used for the lower triangle.
  • Nested loops: These are used to print the exact pattern.

Code

Let’s look at the below code snippet.

# Number of rows
rows = 5
# Upper Triangle
k = 2 * rows - 2
# Outer loop to handle number of rows
for i in range(rows):
#Inner loop to handle number of spaces
for j in range(k):
print(end=" ")
k = k - 1
#Inner loop to print patterns
for j in range(0, i + 1):
print(i+1, end=" ")
print("")
# Lower Triangle
k = rows - 2
# Outer loop to handle number of rows
for i in range(rows, -1, -1):
#Inner loop to handle number of spaces
for j in range(k, 0, -1):
print(end=" ")
k = k + 1
#Inner loop to print patterns
for j in range(0, i + 1):
print(i+1, end=" ")
print("")

Explanation

  • In line 2, we take the input for the number of rows (i.e., the length of one side of the diamond)

  • From lines 5 to 18, we created a for loop to generate the upper triangle.

  • In line 8, we created a for loop to handle the number of rows.

  • In lines 11 to 13, we created a loop to handle the number of spaces.

  • In lines 16 to 18, we created a loop to print the patterns.

    • i+1 is used, so as to start the pattern from 1.
  • From lines 22 to 35, we created a for loop to generate the lower triangle.

  • In line 25, we created a for loop to handle the number of rows.

  • In lines 28 to 30, we created a loop to handle the number of spaces.

  • In lines 33 to 35, we created a loop to print the patterns.

    • As i increases with increases in row number up to 6, and then decreases.

Free Resources