How to generate an inverted hollow equilateral triangle in Python
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.
Description
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:
- An outer loop to handle the number of rows and columns.
- Two inner loops, with one to handle the initial spaces and the other to print the given pattern.
Code
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 columnsfor i in range(n):# Spaces across rowsfor j in range(i):print(" ", end="")# Conditions for creating the patternfor 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
chat line 14, which is used to create alphabets from numbers by using the iterative value ofiand the concept of ASCII conversion. The starting value65 + (i=0)is used as the ASCII value ofA(start of the triangle).
- In line 18, the
print()statement is used to move to a new line.