Python program to print a right angle triangle

Python 3 program to print a right angle triangle :

In this tutorial, we will learn how to print a right angle triangle using python 3. The output will look like as below :

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6

So, we will run two loops here. You can use any loop (for or while) you want. In this example we will use ‘for’ loop. Outer loop will run for 6 times in the example. Let’s say it runs for i from 1 to 6. Inner loop will be used to print the numbers : it will run for 1 to i .
For i =1 for outer loop, j will run for 1 for inner loop
For i = 2 for outer loop, j will run for 1,2 for inner loop
For i = 3 for outer loop, j will run for 1,2,3 for inner loop
For i = 4 for outer loop, j will run for 1,2,3,4 for inner loop
For i = 5 for outer loop, j will run for 1,2,3,4,5 for inner loop
For i = 6 for outer loop, j will run for 1,2,3,4,5,6 for inner loop

For each time inner loop runs, we will print the value of ‘i’ . So, for i = 1, it will print only 1 , for i = 2 , it will print only 2 etc.

Python Program :

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

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

Output:

Enter the height of the triangle :8
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8

Python program to print a right angle triangle using star (*) or any character :

We can modify the above program to print this triangle with any character we want :

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(1,height+1):
	for j in range(1,i+1):
		print(c+" ", end='')
	print()

Sample Outputs :

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

Enter the height of the triangle : 8
Enter the character you want to print the triangle : $
$
$ $
$ $ $
$ $ $ $
$ $ $ $ $
$ $ $ $ $ $
$ $ $ $ $ $ $
$ $ $ $ $ $ $ $

Leave a Reply