This shot will discuss generating a hollow left-angle triangle using alphabets in Python.
We can print a plethora of patterns using Python. The essential and only prerequisite is a good understanding of how loops work in Python. Here, we will be using simple
for loops to generate a hollow left-angled triangle using alphabets.
A triangle is left-angled if and only if it has one angle equal to 90 degrees on its right side.
Let’s take a look at the below code snippet.
# Number of rows n = 8 # Loop through rows for i in range(1,n+1): # Loop through columns for j in range(1, n+1): ch = chr(64+i) # Printing Pattern if (i==n-j+1) or (j==n) or (i==n): print(ch, end=" ") else: print(" ", end=" ") print()
In line 2, we take the input for the number of rows (i.e., triangle length).
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 by using the iterative value of
i and the concept of ASCII conversion. The starting value
64+(i=1) has been used, as the ASCII value of
A (start of the triangle) is
From lines 11 to 14, we create the pattern using conditional statements.
i==n-j+1⇒ creates the hypotenuse of the triangle.
j==n⇒ creates the perpendicular of the triangle.
i==n⇒ creates the base of the triangle.
The end statement helps to stay on the same line.
In line 15, the
print() statement is used to move to the next line.
View all Courses