In this shot, we will discuss how to generate a hollow right-angled triangle using 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 hollow right-angled triangles using alphabets.
A triangle is said to be right-angled if it has an angle equal to 90 degrees on its left side.
To execute the same using Python programming, we will be using 2
Let’s have a look at the code.
# 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==j) or (j==1) or (i==n): 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.
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