Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python
alphabets
triangle

Generate solid right-angled triangle using alphabets in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate a solid right-angled triangle using alphabets in Python.

We can print a plethora of patterns using Python. The essential and only prerequisite is a good understanding of how loops work in Python. Here, we will be using simple for loops to generate solid right-angled triangles using alphabets.

Description

A triangle is said to be right-angled if it has an angle equal to 90 degrees on its left side.

To execute the same using Python programming, we will be using two for loops:

  • An outer loop to handle the number of rows.
  • An inner loop to handle the number of columns.

Code

Let’s have a look at the code.

# Number of rows
rows = 8

# Outer loop to handle the rows
for i in range(rows):
    
    # Inner loop to handle the columns
    for j in range(i + 1):
        ch = chr(65+i)
        # Printing the pattern
        print(ch, end=' ')
    
    # Next Line
    print()

Example code generating a solid right-angled triangle using alphabets

Explanation

  • In line 2, we take the input for the number of rows (i.e., triangle length).

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

  • In line 8, we create an inner nested for loop to iterate through the number of columns.

  • In line 9, 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 the ASCII value of A (starting of the triangle) is 65.

  • In line 11, we print the pattern (here, alphabets). Any other characters could have been printed by mentioning the same in the print statement. The end statement helps us stay on the same line until the loop finishes.

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

RELATED TAGS

communitycreator
python
alphabets
triangle
RELATED COURSES

View all Courses

Keep Exploring