Generate an inverted left-angled triangle using numbers in Python

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.

Description

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:

  • An outer loop to handle the number of rows.
  • Two inner loops, one to handle the initial spaces and the other to print the characters.

Code

Let’s have a look at the code.

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(j+1, end=" ")
print()

Explanation

  • 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.

Free Resources