We can print a plethora of patterns using Python. Here, we use simple for
loops to generate an inverted right-angled triangle using asterisks.
A key prerequisite for this task is a good understanding of how loops work.
A triangle is said to be right-angled if, and only if, it has one angle equal to 90 degrees.
An inverted right-angled triangle is just an upside-down version of a right triangle, with one of its vertices at the bottom.
To make the pattern, we use two for
loops nested within an outer for
loop:
Let’s look at the below code snippet to understand it better.
# Number of rowsrows = 5# 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):# Display patternprint("*", end=' ')print(" ")
In line 2, we take the input for the number of rows (i.e., length of the triangle).
In line 5, we create a for
loop to handle the number of rows. The loop is reversed in nature. This means it starts with the input value and the number of characters to be printed decreases with increasing rows.
In line 8, we create a nested for
loop (inner loop), to handle the number of columns. This follows the same principle as above, both of which help to create an inverted triangle.
In line 11, we print the pattern using *
. The end statement helps us to be on the same line until the loop finishes.
In line 12, we use print()
, to move to the next line.