Related Tags

communitycreator
python

Generate an inverted solid right-angled triangle with alphabets

Vinisha Maheshwari

In this shot, we will learn how to generate an inverted and solid right-angled triangle with alphabets in Python.

We can print a plethora of patterns in Python. The only prerequisite for this is having a good understanding of how loops work in Python. Here, we will use a for loop structure and alphabets to generate an inverted and solid right-angled triangle.

Description

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

We will use a nested for loop:

• Outer loop: Handles the number of rows.
• Inner loop: Handles the number of columns.

Code

Let’s look at the code snippet below.

# Number of rows
rows = 8

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

# Nested reverse loop to handle number of columns
for j in range(0, i-1):
ch = chr(63+i)
# Display pattern
print(ch, end=' ')
print(" ")
Generate an inverted and solid right-angled triangle with alphabets

Code explanation

• Line 2: We declare the input for the number of rows, e.g., the length of the triangle.

• Line 5: We create an outer for loop to handle the number of rows. The loop is reversed one, so it starts with the input value, and the number of characters to print decreases with the increase in rows.

• Line 8: We create a nested inner for loop to handle the number of columns. This follows the same principle as above. The outer loop and inner loop work together to create an inverted triangle.

• Line 9: We define ch, which is used to create alphabets from numbers. ch uses the iterative value of i and the concept of ASCII conversion.

• Line 11: We print the pattern (alphabets). We can also print any other character(s) by mentioning them in the print statement. The end statement allows us to remain on the same line until the loop finishes.

• Line 12: We use the print() function to move on to the next line.

RELATED TAGS

communitycreator
python

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time