Generate solid equilateral triangle using alphabets in Python
In this shot, we will generate a solid equilateral triangle using alphabets in Python.
We can print a plethora of patterns using Python. The only prerequisite to do so is a good understanding of how loops work in Python. Here, we will be using simple for loops to generate a solid equilateral triangle using alphabets.
Description
A triangle is equilateral if it has all three sides of the same length. To create an equilateral triangle with alphabets 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 take a look at the code.
# Number of Rowsn = 8# Number of spacesk = n - 1# Outer loop to handle number of rowsfor i in range(0,n):#Inner loop to handle number of spacesfor j in range(0,k):print(end=" ")# Decrementing k after each loopk -= 1# Inner loop to handle number of columns# Values change acc to outer loopfor j in range (0, i+1):ch = chr(65+i)# Printing Starsprint(ch, end=" ")# Ending Line after each rowprint("\r")
Explanation
-
In line 2, we take the input for the number of rows.
-
In line 5, we define
k, the number of spaces. -
In line 8, we create a loop to handle the number of rows.
-
In lines 11 and 12, we use inner loops to create spaces.
-
In line 15, the value of
kis decremented after every iteration to create the slope. -
In line 19, the loop is created to handle the number of columns.
-
In line 21, we define
ch, which is used to create alphabets from numbers by using the iterative value ofiand the concept of ASCII conversion. The starting value65has been used, as the ASCII value ofA(start of the triangle) is 65. -
In line 24, we print
chto generate an equilateral triangle using characters. -
In line 27, we use
\rto print the stars from the next row.