Generate a solid left angle triangle using alphabets in Python
In this shot, we will discuss how to generate a solid left angle 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 a left-angled triangle using alphabets.
Description
A triangle is said to be left-angled if and only if it has one angle equal to 90 degrees on its right side.
Code
Let us take a look at the code snippet below.
# Number of rowsrows = 8# Iterating value for columnk = 2*rows-2# Loop through rowsfor i in range(rows):# Loop to print initial spacesfor j in range(k):print(end=" ")# Updating value of Kk = k-2# Loop to print the numbersfor j in range(i+1):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).
-
In Line 5, we create the iterating variable
k, which will be used later to handle the number of columns. -
From Lines 8 to 21, we create the outer for loop to iterate through the no of rows.
-
In Lines 11 and 12, we create the first inner nested loop to print the initial spaces.
-
In Line 15, the value of
kis updated, so that the output is a left-angled triangle i.e. the characters are printed from right to left. Unless updated, the triangle would have been a right-angled triangle. -
In Lines 18 to 20, 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 19, 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 ASCII value ofA(starting of the triangle) is65. -
In Line 20, we use
print(), to move to the next line.