We can print a plethora of patterns using Python. The basic and only prerequisite is a good understanding of how loops work in Python. In this shot, we will use simple for
loops to generate an inverted equilateral triangle using stars.
A triangle is said to be equilateral if it has the same length on all three sides. An inverted equilateral triangle will be the inverted form of the same, with its vertex lying on the bottom, pointing downwards.
To execute this using Python programming, we will use two for
loops nested within an outer for
loop:
Let us look at the code snippet below to understand this better.
# User Input for number of rows and columns (Length of Triangle)num = 3# Loop over number of rows and columnsfor i in range(num, 0, -1):# Spaces across rowsfor j in range(0, num-i):print(end=" ")# Print spaced starsfor j in range(0, i):print("*", end=" ")# Go to next lineprint()
In line 2, the user gives input to specify the number of rows and columns, i.e., the length of the triangle
In line 5, we create an outer for
loop to loop over the rows and columns
In lines 8 and 9, we create an inner for
loop to print the initial spaces across the rows.
In lines 12 and 13, we create another inner loop to print the characters and spaces in between them.
In line 16, we use print()
outside the inner loops but inside the outer loop to move to the next line.