Generate an inverted hollow right angled triangle with alphabets
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.
Description
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 for loops:
- An outer loop: To handle the number of rows.
- An inner loop: To handle the number of columns.
Code
Let’s take a look at the code snippet below.
# Number of rowsn = 8# Loop through rowsfor i in range(1,n+1):# Loop through columnsfor j in range(1, n+1):ch = chr(64+i)# Printing Patternif (i==n-j+1) or (j==1) or (i==1):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
forloop to iterate through the number of rows. -
In line 8, we create an inner nested
forloop to iterate through the number of columns. -
In line 9, we define
chwhich is used to create alphabets from numbers by using the iterative value ofiand the concept of ASCII conversion. The starting value 64 + (i=1), has been used as ASCII value ofA(starting of the triangle) is 65. -
From lines 11 to 14, we create the pattern using conditional statements.
- i== n-j+1 ⇒ creates the hypotenuse of the triangle.
- j==1 ⇒ creates the perpendicular of the triangle.
- i==1 ⇒ 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.