How to make a hollow inverted left-angled triangle with numbers
In this shot, we will discuss how to generate a hollow inverted left-angled triangle with numbers in Python. The main prerequisite for this is to have a good understanding of for loops.
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 upside-down version of a left-angled triangle.
To create the pattern, we will use 2 for loops:
- An outer loop: To handle the number of rows.
- An inner loop: To handle the number of columns.
Code
Let’s look at the code snippet below.
# Number of rowsn = 5# Loop through rowsfor i in range(1, n+1):# Loop through columnsfor j in range(1, n+1):# Printing Patternif (j == n) or (i == 1) or (i == j):print(i, end=" ")else:print(" ", end=" ")print()
Explanation
-
In line 2, we take the input for the number of rows (i.e., the length of the triangle). In this case, it is set to 5.
-
In line 5, we create a
forloop to iterate through the number of rows. -
In line 7, we create an inner nested
forloop to iterate through the number of columns. -
From lines 9 to 12, we use conditional statements to create the pattern, and check to see if the character should be printed at that position or if a space character should be added instead. The
endstatement helps to stay on the same line. -
In line 13, we use the
print()statement to move to the next line.