Generate hollow right-angled triangle using alphabets in Python

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.

Description

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 for loops:

  • An outer loop: To handle the number of rows.
  • An inner loop: To handle the number of columns.

Code

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()

Explanation

  • 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.

    • i==j ⇒ creates the hypotenuse of the triangle.
    • j==1 ⇒ 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.

Free Resources