Inverted Triangle pattern in Python

In the previous article we explored the implementation and approach towards Triangle pattern in Python, now we will explore the concept and implementation of the Inverted Triangle pattern in Python. It operates according to the user input, for example for the number 4 it would return:

Output:
****
***
**
*

Implementation/Working of Inverted Triangle pattern in Python

The pattern is dependent upon the number entered by the user, we use the input() function to take in the user entered number ‘n’ , we begin a for loop with the range(0 to n-1). The program goes through the range and prints out a * character for each element in the range. Within the loop another for loop statement reverses the range, and on each iteration reduces the number by one to obtain the reverse or decreasing pattern. The loop is terminated automatically when the number is reduced to 1 and the program stops execution.

n=int(input("Enter n:"))
for i in range(n):
    for j in range(n-i):
        print("*", end=" ")
    print()

Output 1:
Enter n:6
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 
Output 2:
Enter n:14
* * * * * * * * * * * * * * 
* * * * * * * * * * * * * 
* * * * * * * * * * * * 
* * * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * 
* * * * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

We can replace the star symbol with any other value or character, for example the very number entered by the user.

n=int(input("Enter n:"))
for i in range(n):
    for j in range(n-i):
        print(n, end=" ")
    print()

Output:
Enter n:7
7 7 7 7 7 7 7 
7 7 7 7 7 7 
7 7 7 7 7 
7 7 7 7 
7 7 7 
7 7 
7 

The program is able to print out the character pattern of the inverted triangle as expected, and is able to do so with the help of incorporated nested loops. in the next article we will explore similar logic but to obtain a pyramid style pattern.

Leave a Comment