Related Tags

communitycreator
python
triangle

How to generate an inverted equilateral triangle with numbers

Vinisha Maheshwari

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

We can print a plethora of patterns using Python. The basic and only prerequisite is a good understanding of how loops work in Python. In this shot, we will use simple for loops to generate an inverted equilateral triangle using numbers.

Description

A triangle is said to be equilateral if it has the same length on all three sides. An inverted equilateral triangle is the inverted form of the same with its vertex lying on the bottom, pointing downwards.

To execute this using Python programming, we will use two for loops nested within an outer for loop:

• The outer loop will handle the number of rows and columns.
• One inner loop will handle the initial spaces and the other inner loop will handle spaces in between the characters as well as print the characters.

Code

Let us look at the code snippet below.

# User Input for number of rows and columns (Length of Triangle)
num = 6

# Loop over number of rows and columns
for i in range(num, 0, -1):

# Spaces across rows
for j in range(0, num-i):
print(end=" ")

# Print spaced stars
for j in range(0, i):
print(i, end=" ")

# Go to next line
print()



Explanation

• In line 2, the user gives input to specify the number of rows and columns, i.e., the length of the triangle.

• In line 5, we create an outer for loop to loop over the rows and columns

• In lines 8 and 9, we create an inner for loop to print the initial spaces across the rows.

• In line 12, we create another inner loop.

• In line 13, we have printed i which starts with 6 and as it comes down to the rows below, its value gets decremented by $1$.

RELATED TAGS

communitycreator
python
triangle

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time