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
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 spaces
i = 5==> 6 - 5 = 5 spaces
i = 4==> 6 - 4 = 4 spaces and so on
In lines 12 to 14, we create our second inner loop to print the characters and spaces in between them.
i = 6==> therefore 6 characters
i = 5==> therefore 6 characters
i = 4==> therefore 4 stars … and so on
end = " "gives spaces between characters
Note: We have defined
chwhich is used to create alphabets from numbers by using the iterative value of
iand the concept of ASCII conversion. The starting value
64+(i=1)has been used as ASCII value of
A(starting of the triangle).
print()outside the inner loops but inside the outer loop to move to the next line.
View all Courses