In this shot, we will discuss how to generate an inverted left-angled triangle using numbers in Python.
We can print a plethora of patterns using Python. The basic and only prerequisite to do this is a good understanding of how loops work in Python. Here, we will be using a simple for
loops to generate an inverted left-angled triangle using numbers.
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 just the inverted form of the same with its vertex lying on the bottom.
To execute the same using Python programming, we will be using two for
loops nested within an outer for
loop:
Let’s have a look at the code.
rows = 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(j+1, 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 line 13, we print j+1
, which results in iteration from 1 (since j + 1) to a length of (row-i) in each row. i
keeps increasing after every iteration, and so the number of integers keeps decreasing.
In line 14, we use print()
to move to the next line.
In this way, we can generate an inverted left-angled triangle using numbers in Python.