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