Generate solid right-angled triangle using alphabets in Python
In this shot, we will discuss how to generate a solid right-angled triangle using alphabets in Python.
We can print a plethora of patterns using Python. The essential and only prerequisite is a good understanding of how loops work in Python. Here, we will be using simple for loops to generate solid 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 two 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 rowsrows = 8# Outer loop to handle the rowsfor i in range(rows):# Inner loop to handle the columnsfor j in range(i + 1):ch = chr(65+i)# Printing the patternprint(ch, end=' ')# Next Lineprint()
Explanation
-
In line 2, we take the input for the number of rows (i.e., triangle length).
-
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
ch, which is used to create alphabets from numbers by using the iterative value ofiand the concept of ASCII conversion. The starting value65+(i=0)has been used, as the ASCII value ofA(starting of the triangle) is65. -
In line 11, we print the pattern (here, alphabets). Any other characters could have been printed by mentioning the same in the print statement. The end statement helps us stay on the same line until the loop finishes.
-
In line 14, we use
print()to move to the next line.