Generate an inverted hollow right-angled triangle with stars
In this shot, we will discuss how to generate an inverted hollow right-angled triangle using stars in Python. We can print a plethora of patterns with Python. The only prerequisite is a good understanding of how loops work in Python. Here, we will use simple for loops to generate an inverted hollow right-angled triangle with stars.
Description
A triangle is said to be right-angled if it has an angle equal to 90 degrees on its left side. An inverted right-angled triangle is just the inverted form of the same with its vertex lying on the bottom.
To print an inverted right-angled triangle in Python, we will use 2 for loops:
- Outer loop: To handle the number of rows.
- Inner loop: To handle the number of columns.
Code
Let’s look at the code snippet below.
# Number of rowsn = 5# Loop through rowsfor i in range(1,n+1):# Loop through columnsfor j in range(1, n+1):# Printing Patternif (i==n-j+1) or (j==1) or (i==1):print("*", end=" ")else:print(" ", end=" ")print()
Explanation
-
In line 2, we take the input for the number of rows (i.e., the length of the triangle).
-
In line 5, we create a
forloop to iterate through the number of rows. -
In line 8, we create an inner nested
forloop to iterate through the number of columns. -
From lines 11 to 14, we use conditional statements to create the pattern. The
endstatement helps to stay on the same line. -
In line 15, we use the
print()statement to move to the next line.
In this way, we can generate an inverted hollow right-angled triangle using stars in Python.