Generate an inverted hollow equilateral triangle using numbers
Overview
This shot will discuss how to generate an inverted hollow equilateral triangle using numbers in Python.
Methodology
We can print a plethora of patterns using Python. The fundamental and only prerequisite to do so is a good understanding of how loops work in Python.
Here, we will be using simple
forloops to generate an inverted hollow equilateral triangle using numbers.
Description
An equilateral triangle has three sides of the same length. A hollow inverted equilateral triangle will be the inverted form of this, with its vertex lying on the bottom and the integers inside empty.
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: One to handle the initial spaces and the other to print the given pattern.
Code
def inverted_hollow_triangle(n):# 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:print(i, end=" ")else:print(" ", end=" ")print()inverted_hollow_triangle(5)
Explanation
-
In line 4, we create a loop to iterate over the number of rows.
-
In line 7 and 8, we created a loop that gives the initial spaces (before characters) across each row.
-
From lines 11 to 15, we created our second inner loop to form the given pattern.
-
In lines 13 to 15, we specified that whenever these conditions are met, an integer is printed, and 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.