Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python
triangle

How to make an inverted right-angled triangle using asterisks

Vinisha Maheshwari

We can print a plethora of patterns using Python. Here, we use simple for loops to generate an inverted right-angled triangle using asterisks.

A key prerequisite for this task is a good understanding of how loops work.

Description

A triangle is said to be right-angled if, and only if, it has one angle equal to 90 degrees.

An inverted right-angled triangle is just an upside-down version of a right triangle, with one of its vertices at the bottom.

Algorithm

To make the pattern, we use two for loops nested within an outer for loop:

  • 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 to understand it better.

# 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("*", end=' ')
    print(" ")

Explanation

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

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

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

  • In line 11, we print the pattern using *. The end statement helps us to be on the same line until the loop finishes.

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

RELATED TAGS

communitycreator
python
triangle
RELATED COURSES

View all Courses

Keep Exploring