Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

Generate an inverted left-angled triangle using stars in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate an inverted left-angled triangle using stars in Python.

We can print a plethora of patterns using Python. The basic and only prerequisite is understanding how loops work in Python. Here, we will use simple for loops to generate an inverted left-angled triangle using stars.

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 the inverted form of the same triangle, with its vertex lying on the bottom.

To execute this in Python programming, we use two for loops nested within an outer for loop.

The purpose of these loops is as follows:

  • Outer loop: To handle the number of rows.
  • Inner loops: One to handle the initial spaces and the other to print the characters.

Code

Let’s have a look at the code.

# Number of rows
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("*", 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 lines 12 and 13, we create our second inner nested loop to print the character (*). The end statement keeps us on the same line until the loop finishes.

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

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

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring