Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate an inverted right-angled triangle in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate an inverted right-angled triangle using numbers 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 right-angled triangle using numbers.

Description

A triangle is said to be right-angled if it has an angle equal to 90 degrees on its left side. An inverted right-angled triangle is just the inverted form of this with its vertex lying on the bottom.

To execute this 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 below code snippet.

# Number of rows
rows = 5

# Loop over number of rows 
for i in range(rows+1, 0, -1):
    
    # Nested reverse loop to handle number of columns
    for j in range(0, i-1):
        
        # Display pattern
        print(j+1, end=' ')
    print(" ")

Explanation

  • In line 2, the input for the number of rows (i.e., length of the triangle) is taken.

  • In line 5, we create a for loop to handle the number of rows. The loop is a reversed one, i.e., it starts with the input value, and with increasing rows, the number of characters to be printed decreases.

  • In line 8, we create a nested for loop (inner loop), to handle the number of columns. This follows the same principle as above, which help together to create an inverted triangle.

  • In line 11, we have printed j+1, which results in iteration from 1 (since j + 1) to a length of (row-i) in each row. As i keeps increasing after every iteration, the number of integers keeps decreasing.

  • In line 12, we use print(), to move to the next line.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring