Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

Generate an inverted left angle triangle with alphabets in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate an inverted left angle triangle with alphabets in Python.

We can print a plethora of patterns using python. The basic and only prerequisite for the same is a good understanding of how loops work in Python. Here we will be using simple for loops to generate inverted solid and hollow left-angled triangles using alphabets.

Description

A triangle is said to be left-angled if it has an angle equal to 90 degrees on its right side. An inverted left-angled triangle is just the inverted form of the same with its vertex lying on the bottom.

Code

Let’s look at the code snippet below.

# Number of rows
rows = 8

# 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):
        ch = chr(65+i)
        print(ch, 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 15, we create the outer for loop to iterate through the no of rows.

  • In lines 8 and 9, we create the first inner nested loop to print the initial spaces.

  • In lines 12 to 14, we create our second inner nested loop to print the characters (here alphabets). The end statement helps us to be on the same line till the loop finishes.

  • In line 13, we define 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 65 + (i=0), has been used as ASCII value of A (starting of the triangle) is 65.

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

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring