In this shot, we will discuss how to generate an inverted hollow right-angled triangle with alphabets in Python.
We can print a plethora of patterns using python. The basic and only prerequisite for the same is a good understanding of how loops work in Python. Here we will be using simple
for loops to generate an inverted hollow right-angled triangle using alphabets.
A triangle is said to be right-angled if it has an angle equal to 90 degrees on its left side. An inverted right-angled triangle is just the inverted form of the same with its vertex lying on the bottom.
To execute the same using Python programming, we will be using 2
Let’s take a look at the code snippet below.
# 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==1) or (i==1): print(ch, end=" ") else: print(" ", end=" ") print()
In line 2, we take the input for the number of rows (i.e., 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 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 of the triangle) is 65.
From lines 11 to 14, we create the pattern using conditional statements.
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