Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

Generate an inverted hollow right-angled triangle with stars

Vinisha Maheshwari

In this shot, we will discuss how to generate an inverted hollow right-angled triangle using stars in Python. We can print a plethora of patterns with Python. The only prerequisite is a good understanding of how loops work in Python. Here, we will use simple for loops to generate an inverted hollow right-angled triangle with stars.

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 the same with its vertex lying on the bottom.

To print an inverted right-angled triangle in Python, we will use 2 for loops:

  • Outer loop: To handle the number of rows.
  • Inner loop: To handle the number of columns.

Code

Let’s 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("*", 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 use conditional statements to create the pattern. The end statement helps to stay on the same line.

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

In this way, we can generate an inverted hollow right-angled triangle using stars in Python.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring