Mhd Ridho Swasta
Mhd Ridho Swasta

Reputation: 117

How to print a triangle in python?

I want to make a function to print triangle like the following picture. User can insert the row number of the triangle. The total lenght of first row is must an odd.

I try to use below code :

def triangle(n): 
    k = 2*n - 2
    for i in range(0, n): 
        for j in range(0, k): 
            print(end=" ") 
        k = k - 1
        for j in range(0, i+1): 
            print("* ", end="") 
        print("\r") 
n = 5
triangle(n) 

Here is the expected output image :

expected output

and here is my actual output image :

real output

but I can't remove the star middle star. And it's not Upside - Down Triangle

Upvotes: 2

Views: 3338

Answers (3)

Humaun Rashid Nayan
Humaun Rashid Nayan

Reputation: 1242

You could try a different way.

def triangle(n) : 

    for i in range(1,n+1) : 

        for j in range(1,i) : 
            print (" ",end="") 

        for j in range(1,(n * 2 - (2 * i - 1))  
                                       +1) : 
            if (i == 1 or j == 1 or 
               j == (n * 2 - (2 * i - 1))) : 
                print ("*", end="")  
            else : 
                print(" ", end="")  

        print ("")

n = 5
triangle(n) 

Upvotes: 2

Akash Kumar
Akash Kumar

Reputation: 1406

Not sure how cool implementation is this but it gives results:

def triangle(n): 
    print(' '.join(['*']*(n+2)))
    s = int((n/2)+1)
    for i in range(s):
        star_list = ['  ']*(n+2)
        star_list[-i-2] = ' *'
        star_list[i+1] = '*'
        print(''.join(star_list))

n = 5
triangle(n) 

Output:

* * * * * * *
  *       *  
    *   *    
      *   

for n = 7:

* * * * * * * * *
  *           *  
    *       *    
      *   *      
        *  

Upvotes: 1

Riley Simpson
Riley Simpson

Reputation: 7

I would try a recursive solution where you call the printTriangle() function. This way, it will print the point first and move it's way down the call stack.

Upvotes: 0

Related Questions