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
The purpose of these loops is as follows:
Let’s have a look at the code.
# Number of rows rows = 5 # Loop through rows for i in range(rows): # Loop to print initial spaces for j in range(i): print(" ", end=" ") # Loop to print the stars for 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 (
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.
View all Courses