In this shot, we will discuss how to generate an inverted solid equilateral triangle using alphabets.
We can print a plethora of patterns using Python. The basic and only prerequisite is a good understanding of how loops work in Python. Here we will be using simple for
loops to generate inverted solid equilateral triangle using alphabets.
An equilateral triangle is one which has all its 3 sides of the same length. An inverted equilateral triangle will just be the inverted form of the same with its vertex lying on the bottom. To execute the same using Python programming, we will be using two for
loops nested within an outer for
loop:
Let’s have a look at the code.
# User Input for number of rows and columns (Length of Triangle) num = 8 # Loop over number of rows and columns for i in range(num, 0, -1): # Spaces across rows for j in range(0, num-i): print(end=" ") # Print spaced alphabets for j in range(0, i): ch = chr(64+i) print(ch, end=" ") # Go to next line print()
In line 2, the user gives input to specify the number of rows and columns i.e., length of triangle.
In line 5, we create an outer for
loop to loop over the rows and columns.
In lines 8 and 9, we create an inner for
loop to print the initial spaces across the rows Num - i
.
i = 6
==> 6 - 6 = 0 spacesi = 5
==> 6 - 5 = 5 spacesi = 4
==> 6 - 4 = 4 spaces and so onIn lines 12 to 14, we create our second inner loop to print the characters and spaces in between them.
i = 6
==> therefore 6 charactersi = 5
==> therefore 6 charactersi = 4
==> therefore 4 stars … and so onend = " "
gives spaces between charactersNote: We have defined
ch
which is used to create alphabets from numbers by using the iterative value ofi
and the concept of ASCII conversion. The starting value64+(i=1)
has been used as ASCII value ofA
(starting of the triangle).
print()
outside the inner loops but inside the outer loop to move to the next line.RELATED TAGS
CONTRIBUTOR
View all Courses