Generate an inverted hollow left angled triangle using stars
In this shot, we will discuss how to generate an inverted hollow left angled triangle using stars in Python.
We can print a plethora of patterns using Python. The only prerequisite to do this is a good understanding of how loops work in Python. Here, we will be using simple for loops to generate an inverted hollow left-angled triangle using stars.
Description
A triangle is said to be left-angled if it has an angle equal to 90 degrees on its right side. An inverted left-angled triangle is just the inverted form of that, with its vertex lying on the bottom.
To execute an inverted left-angled triangle using Python programming, we will be using two for loops:
- An outer loop: To handle the number of rows.
- An 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 (j==n) or (i==1) or (i==j):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 create the pattern using conditional statements. The end statement helps to stay on the same line.
-
In line 15, the
print()statement is used to move to the next line.
In this way, we generate an inverted hollow left-angled triangle using stars in Python.