Python program to print a triangle using star

Python 3 program to print a Triangle using star :

In this tutorial, we will learn how to print a triangle using star ( * ) . You can change it to any other characters if you want. User will enter the height of the triangle and the triangle will be print. It is a right angle triangle. Let’s take a look :

Printing triangle using star :

The program to print triangle using star is as below :

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

for i in range(height,0,-1):
    print(i* ' ' + (height+1-i) * '*')

Let’s check some examples how it will print :

 

 

How the example is working ? To understand the concept, let’s do some modification to the program :

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

for i in range(height,0,-1):
    print(i* 'k' + (height+1-i) * '*')

Only thing we have changed is that we are printing out ‘k’ instead of a space . It will result as like below :

Enter the height of the triangle : 5
kkkkk*
kkkk**
kkk***
kk****
k*****

So, we found that :
1. ‘k’ is printed instead of space ‘ ‘. Think ‘k’ as space.
2. For the first line, ‘k’ is printed for ‘height‘ times and ‘*’ for 1 time
3. For the second line, ‘k’ is printed for ‘height – 1’ times and ‘*’ for 2 time.
4. For the third line, ‘k’ is printed for ‘height – 2’ times and ‘*’ for 3 times.
5. There are ‘height‘ lines.

Now, let’s try to understand the program :

1. We have a ‘for‘ loop that runs (height) times. ‘i’ is the value in this loop. ‘i’ will run from value (height + 1) to 1. Each time it will be decremented by 1.
2. Inside the loop, first space ‘ ‘ is printed for ‘i’ times and then ‘*’ is printed for (height + 1 -i) times.
3. That’s it. You can write down each step of the loop to understand the program better.

Sitewide-USD 336x280

Leave a Reply