In this shot, we will discuss how to generate an inverted left-angled triangle using stars in Python.
We can print a plethora of patterns using Python. The basic and only prerequisite is understanding how loops work in Python. Here, we will use simple for
loops to generate an inverted left-angled triangle using stars.
A triangle is said to be left-angled if it has an angle equal to 90 degrees on its left side. An inverted left-angled triangle is the inverted form of the same triangle, with its vertex lying on the bottom.
To execute this in Python programming, we use two for
loops nested within an outer for
loop.
The purpose of these loops is as follows:
Let’s have a look at the code.
# Number of rowsrows = 5# Loop through rowsfor i in range(rows):# Loop to print initial spacesfor j in range(i):print(" ", end=" ")# Loop to print the starsfor j in range(rows-i):print("*", end=" ")print()
In line 2, we take the input for the number of rows (i.e., length of the triangle).
From lines 5 to 14, we create the outer for
loop to iterate through the number of rows.
In lines 8 and 9, we create the first inner nested loop to print the initial spaces.
In lines 12 and 13, we create our second inner nested loop to print the character (*
). The end
statement keeps us on the same line until the loop finishes.
In line 14, we use print()
to move to the next line.
In this way, we can generate an inverted left-angled triangle using stars in Python.