Python 3 program to print invert right angle triangle

Python 3 program to print invert right angle triangle using number :

height = int(input("Enter the height of the triangle : "))

for i in range(1,height+1):
	for j in range(1,height - i+2):
		print(str(j)+" ", end='')
	print()

Output :

Enter the height of the triangle : 5
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

How it works ?

In this example, we are printing a invert right angle triangle using numbers. The numbers are printed serially like 1,2,3,4,5…. . If height is 5 : for the first line, we are printing one numbers ‘1,2,3,4,5′, for the second line we are printing 4 numbers ‘1,2,3,4’ , third line three numbers ‘1,2,3’ etc.

– First we take the input from the user : the height of the triangle
– We run one ‘for‘ loop from i = 1 to i = height .
– For each loop , we run one more internal loop to print the numbers of the triangle.
– The inner loop runs from j = 1 to j = height – i +2 i.e. if height is 5, for first time, it will run in range j = 1 to j = 5 – 1 + 2 = 6 or for 5 time, for second time, it will run j = 1 to j = 5 or for 4 times etc.
– The inner loop prints out the numbers serially.

We can also print the same invert triangle using any character . Let’s check :

Python 3 program to print invert right angle triangle using any character :

height = int(input("Enter the height of the triangle : "))
c = str(input("Enter the character you want to print the triangle : "))

for i in range(0,height):
	for j in range(0,height - i):
		print(c+" ", end='')
	print()

Output :

Enter the height of the triangle : 5
Enter the character you want to print the triangle : *
* * * * *
* * * *
* * *
* *
*

How it works ?

This example is same as the above one. We are running two ‘for’ loops : the outer one will run for the same number of times as the height of the triangle and the inner one will run based on the height. Unlike previous example, we are printing a character to create the triangle. The character is also Given by the user. Here, we are using ‘*’ to create the triangle but we can use ‘$’,’&’,’#’ etc. anything we want.

Sitewide-USD 336x280

Leave a Reply