Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python
triangle

How to generate an inverted hollow right triangle in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate an inverted hollow right triangle using numbers in Python.

We can print a plethora of patterns using Python. The only prerequisite for this is a good understanding of how loops work in Python. Here we will be using simple for loops to generate an inverted hollow right triangle using numbers.

Description

A triangle is said to be a right triangle if it has a 9090 degree angle. In this shot, we use the term inverted to mean upside down, so the right angle is on the top of the triangle.

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 us look at the code snippet. below:

# Number of rows
n = 5

# Loop through rows
for i in range(1,n+1):
    
    # Loop through columns
    for j in range(1, n+1):
        
        # Printing Pattern
        if (i==n-j+1) or (j==1) or (i==1):
            print(i, end=" ")
        else:
            print(" ", end=" ")
    print()  

Explanation

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

  • In line 5, we create a for loop to iterate through the number of rows.

  • In line 8, we create an inner nested for loop to iterate through the number of columns.

  • From lines 11 to 14, we create the pattern using conditional statements. The end statement helps to stay on the same line.

  • In line 15, the print() statement is used to move to the next line.

RELATED TAGS

communitycreator
python
triangle
RELATED COURSES

View all Courses

Keep Exploring