In this shot, we will discuss how to generate an inverted hollow 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 an inverted hollow equilateral triangle using alphabets.
An equilateral triangle is one which has all three sides of the same length. An inverted equilateral triangle will just be the inverted form of this shape, with its vertex lying on the bottom.
To execute this shape 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) n = 8 # Loop over number of rows and columns for i in range(n): # Spaces across rows for j in range(i): print(" ", end="") # Conditions for creating the pattern for k in range(2*(n-i)-1): if k==0 or k==2*(n-i-1) or i==0: ch = chr(65+i) print(ch, end="") else: print(" ", end="") print()
In line 2, we take the input for the number of rows.
In line 5, we create a loop to iterate over the number of rows.
In line 8 and 9, we create a loop that gives the initial spaces (before characters) across each row.
From lines 12 to 17, we create our second inner loop to form the given pattern.
k==0
⇒ is used to print the left side of the triangle.k==2*(n-i-1)
⇒ is used to print the right side of the triangle.i==0
⇒ is used to print the base of the triangle, which is at the top.Note: We defined
ch
at line 14, which is used to create alphabets from numbers by using the iterative value ofi
and the concept of ASCII conversion. The starting value65 + (i=0)
is used as the ASCII value ofA
(start of the triangle).
print()
statement is used to move to a new line.RELATED TAGS
CONTRIBUTOR
View all Courses