Generate an inverted left angle triangle with alphabets in Python
In this shot, we will discuss how to generate an inverted left angle 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 inverted solid and hollow left-angled triangles using alphabets.
Description
A triangle is said to be left-angled if it has an angle equal to 90 degrees on its right side. An inverted left-angled triangle is just the inverted form of the same with its vertex lying on the bottom.
Code
Let’s look at the code snippet below.
# Number of rowsrows = 8# Loop through rowsfor i in range(rows):# Loop to print initial spacesfor j in range(i):print(" ", end="")# Loop to print the starsfor j in range(rows-i):ch = chr(65+i)print(ch, end="")print()
Explanation
-
In line 2, we take the input for the number of rows (i.e., length of the triangle).
-
From lines 5 to 15, we create the outer for loop to iterate through the no of rows.
-
In lines 8 and 9, we create the first inner nested loop to print the initial spaces.
-
In lines 12 to 14, we create our second inner nested loop to print the characters (here alphabets). The end statement helps us to be on the same line till the loop finishes.
-
In line 13, we define
chwhich is used to create alphabets from numbers by using the iterative value ofiand the concept of ASCII conversion. The starting value 65 + (i=0), has been used as ASCII value ofA(starting of the triangle) is 65. -
In line 14, we use
print()to move to the next line.