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 rowsrow = 5# Upper part of hollow diamondfor 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 diamondfor 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
forloop to generate the upper triangle. -
In line 5, we create a
forloop to handle the number of rows. -
In lines 6-7, we create a
forloop to handle the number of spaces. -
In lines 8 to 14, we create a
forloop to print the patterns.chis used to create letters from numbers by using the iterative value ofiand the concept of conversion. The starting valueASCII American Standard Code for Information Interchange 64 + (i=1)has been used as ASCII value ofA(starting the diamond is 65).j==1creates the left arm of the triangle.j==2*i-1creates the right arm of the triangle.- The
endstatement 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
forloop to generate the lower triangle. -
In line 17, we create a
forloop to handle the number of rows. -
In lines 18-19, we create a
forloop to handle the number of spaces. -
In lines 20-26, we create a
forloop to print the patterns.chis used to create letters from numbers by using the iterative value ofiand the concept of ASCII conversion. The starting value64 + (i=1), has been used as ASCII value ofA(starting the diamond is 65).j==1creates the left arm of the triangle.j==2*i-1creates the right arm of the triangle.- The
endstatement is used to stay on the same line. - The
print()statement is used to move to the next line.
Free Resources
- undefined by undefined