In this shot, we will discuss how to generate an inverted hollow equilateral triangle using asterisks in Python.
We can print a plethora of patterns using Python. A prerequisite for doing so is having a good understanding of loops.
Here, we will be using simple for
loops to generate the inverted triangle.
A triangle is said to be equilateral if all three sides are of the same length. An inverted equilateral triangle is an upside-down triangle with equal sides.
To execute it using Python, we will be using two for
loops nested within an outer for
loop:
Let’s look at the code snippet below.
def inverted_hollow_triangle(n): # 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: print("*", end="") else: print(" ", end="") print() inverted_hollow_triangle(9)
In line 4, we create a loop to iterate over the number of rows.
In lines 7 and 8, we create a loop that gives the initial spaces (before characters) across each row.
In lines 11 to 15, we create another inner loop to form the given pattern.
In lines 13 to 15, we specify that whenever the condition for either being the left asterisk or the right asterisk is met, a *
is printed. In case the conditions aren’t met, we print empty spaces.
In line 16, the print()
statement is used to move to a new line.
RELATED TAGS
CONTRIBUTOR
View all Courses