Generate an inverted solid right-angled triangle with alphabets
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 rowsrows = 8# Loop over number of rowsfor i in range(rows+1, 0, -1):# Nested reverse loop to handle number of columnsfor j in range(0, i-1):ch = chr(63+i)# Display patternprint(ch, end=' ')print(" ")
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
forloop 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
forloop 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.chuses the iterative value ofiand 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
endstatement 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.