How to generate a hollow diamond pattern using letters in Python

This shot will discuss how to generate a hollow diamond pattern using letters of the alphabet in Python.

Numerous patterns can be printed using Python once we have a firm grip over the loops concepts. Here we will be using simple for loops to generate a hollow diamond pattern using letters of the alphabet in Python.

Description

To execute a diamond pattern using Python programming, we will be using 2 outer for loops, one for the upper triangle and the other for the lower triangle, and 4 nested loops to print the pattern.

Code

Let’s have a look at the code.

# Number of rows
row = 5
# Upper part of hollow diamond
for i in range(1, row+1):
for j in range(1,row-i+1):
print(" ", end="")
for j in range(1, 2*i):
ch = chr(64+i)
if j==1 or j==2*i-1:
print(ch, end="")
else:
print(" ", end="")
print()
# Lower part of hollow diamond
for i in range(row-1,0, -1):
for j in range(1,row-i+1):
print(" ", end="")
for j in range(1, 2*i):
if j==1 or j==2*i-1:
ch = chr(64+i)
print(ch, end="")
else:
print(" ", 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).

  • In lines 5-14, we create a for loop to generate the upper triangle.

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

  • In lines 6-7, we create a for loop to handle the number of spaces.

  • In lines 8 to 14, we create a for loop to print the patterns.

    • ch is used to create letters from numbers by using the iterative value of i and the concept of ASCIIAmerican Standard Code for Information Interchange conversion. The starting value 64 + (i=1) has been used as ASCII value of A (starting the diamond is 65).
    • j==1 creates the left arm of the triangle.
    • j==2*i-1 creates the right arm of the triangle.
    • The end statement is used to stay on the same line.
    • The print() statement is used to move to the next line.
  • In lines 17-26, we create a for loop to generate the lower triangle.

  • In line 17, we create a for loop to handle the number of rows.

  • In lines 18-19, we create a for loop to handle the number of spaces.

  • In lines 20-26, we create a for loop to print the patterns.

    • ch is used to create letters from numbers by using the iterative value of i and the concept of ASCII conversion. The starting value 64 + (i=1), has been used as ASCII value of A (starting the diamond is 65).
    • j==1 creates the left arm of the triangle.
    • j==2*i-1 creates the right arm of the triangle.
    • The end statement is used to stay on the same line.
    • The print() statement is used to move to the next line.

Free Resources

Attributions:
  1. undefined by undefined