In this shot, we will learn how to generate an inverted hollow left-angled triangle with alphabets in Python.
We can print a plethora of patterns using Python. The only prerequisite for this is a good understanding of how loops work in Python. Here, we will use simple for
loops and alphabets to generate inverted hollow left-angled triangles.
A triangle is left-angled if it has an angle that is equal to 90 degrees, on its right side. An inverted left-angled triangle is just the inverted form of the same triangle, with its vertex lying on the bottom.
Let’s look at the code snippet:
# Number of rowsn = 8# Loop through rowsfor i in range(1,n+1):# Loop through columnsfor j in range(1, n+1):ch = chr(64+i)# Printing Patternif (j==n) or (i==1) or (i==j):print(ch, end=" ")else:print(" ", end=" ")print()
In line 2, we take the input for the number of rows, that is, the length of the triangle.
In line 5, we create a for
loop to iterate through the number of rows.
In line 8, we create an inner nested for
loop to iterate through the number of columns.
In line 9, we define ch
, which is used to create alphabets from numbers. It uses the iterative value of i
and the concept of ASCII conversion to create alphabets from numbers. The starting value 64 + (i=1)
is used as the ASCII value of A
(starting of the triangle), which is is 65
.
In lines 11–14, we create the pattern, using conditional statements.
j==n
⇒ creates the perpendicular of the trianglei==1
⇒ creates the base of the trianglei==j
⇒ creates the hypotenuse of the triangleThe end
statement helps us stay on the same line.
In line 15, the print()
statement is used to move to the next line.
Free Resources