Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate an inverted hollow equilateral triangle in Python

Vinisha Maheshwari

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

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

Description

An equilateral triangle is one which has all three sides of the same length. An inverted equilateral triangle will just be the inverted form of this shape, with its vertex lying on the bottom.

To execute this shape 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, with 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)
n = 8
    
# Loop over number of rows and columns
for i in range(n):
        
    # Spaces across rows
    for j in range(i):
        print(" ", end="")
            
    # Conditions for creating the pattern
    for k in range(2*(n-i)-1):
        if k==0 or k==2*(n-i-1) or i==0:
            ch = chr(65+i)
            print(ch, end="")
        else:
            print(" ", end="")
    print()

Generating an inverted hollow equilateral triangle
  • In line 2, we take the input for the number of rows.

  • In line 5, we create a loop to iterate over the number of rows.

  • In line 8 and 9, we create a loop that gives the initial spaces (before characters) across each row.

  • From lines 12 to 17, we create our second inner loop to form the given pattern.

    • k==0 ⇒ is used to print the left side of the triangle.
    • k==2*(n-i-1) ⇒ is used to print the right side of the triangle.
    • i==0 ⇒ is used to print the base of the triangle, which is at the top.

Note: We defined ch at line 14, which is used to create alphabets from numbers by using the iterative value of i and the concept of ASCII conversion. The starting value 65 + (i=0) is used as the ASCII value of A (start of the triangle).

  • In line 18, the print() statement is used to move to a new line.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring