Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate an inverted solid equilateral triangle in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate an inverted solid equilateral triangle using alphabets.

We can print a plethora of patterns using Python. The basic and only prerequisite is a good understanding of how loops work in Python. Here we will be using simple for loops to generate inverted solid equilateral triangle using alphabets.

Description

An equilateral triangle is one which has all its 3 sides of the same length. An inverted equilateral triangle will just be the inverted form of the same with its vertex lying on the bottom. To execute the same using Python programming, we will be using two for loops nested within an outer for loop:

  • An outer loop: To handle the number of rows and columns.
  • Two inner loops: One to handle the initial spaces and the other to print the given pattern.

Code

Let’s have a look at the code.

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

# 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 alphabets
    for j in range(0, i):
        ch = chr(64+i)
        print(ch, end=" ")
    
    # Go to next line
    print()

Generating an inverted solid equilateral triangle

Explanation

  • In line 2, the user gives input to specify the number of rows and columns i.e., length of 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 Num - i.

    • i = 6 ==> 6 - 6 = 0 spaces
    • i = 5 ==> 6 - 5 = 5 spaces
    • i = 4 ==> 6 - 4 = 4 spaces and so on
  • In lines 12 to 14, we create our second inner loop to print the characters and spaces in between them.

    • Initially i = 6 ==> therefore 6 characters
    • Next i = 5 ==> therefore 6 characters
    • Next i = 4 ==> therefore 4 stars … and so on
    • end = " " gives spaces between characters

Note: We have defined ch which is used to create alphabets from numbers by using the iterative value of i and the concept of ASCII conversion. The starting value 64+(i=1) has been used as ASCII value of A (starting of the triangle).

  • Finally in line 17, we use the print() outside the inner loops but inside the outer loop to move to the next line.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring