Making an inverted hollow left-angled triangle with alphabets

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.

Description

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.

Code

Let’s look at the 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 (j==n) or (i==1) or (i==j):
print(ch, end=" ")
else:
print(" ", end=" ")
print()

Explanation

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

Attributions:
  1. undefined by undefined
  2. undefined by undefined