JustaGuy313
JustaGuy313

Reputation: 603

How to make a triangle of x's in python?

How would I write a function that produces a triangle like this:

    x
   xx
  xxx
 xxxx
xxxxx

Let's say the function is def triangle(n), the bottom row would have n amount of x's

All I know how to do is make a box:

n = 5
for k in range(n):
    for j in range(n):
        print('x', end='')
    print()

Upvotes: -2

Views: 31348

Answers (6)

Andika Piyo
Andika Piyo

Reputation: 1

(bcs there's people told me to edit my answer i'll edit my answer) Here if you wanna make a upside down triangle :

n = 5
for i in range(n+1, 0, -1):
    print(' '* (n-(i-1)) + '*'*i + '*'*(i-1))

thank you for reminding me:)

output :

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

Upvotes: -3

Ucytochi
Ucytochi

Reputation: 1

def triangle(n):
    x = ('')
    for i in range(n, 0, -1):
        x += '*'
        print(' ' * (i + 1) + x)

Upvotes: 0

Ashish Gupta
Ashish Gupta

Reputation: 1241

Answer:

def triangle(i, t=0):
    if i == 0:
        return 0
    else:
        print ' ' * ( t + 1 ) + '*' * ( i * 2 - 1 )
        return triangle( i - 1, t + 1 )
triangle(5) 

Output:

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

Upvotes: 0

Anonymous User
Anonymous User

Reputation: 65

hight = 5
for star in range(hight):
    for num in range(hight):
        print('*' if num+star >= hight-1 else ' ', end='')
    print()

Upvotes: 0

jackcogdill
jackcogdill

Reputation: 5122

Dude It's super easy:

def triangle(n):
    for i in range(1, n +1):
        print ' ' * (n - i) + 'x' * i

Or even:

def triangle(n):
    for i in range(1, n +1):
        print ('x' * i).rjust(n, ' ')

output for triangle(5):

    x
   xx
  xxx
 xxxx
xxxxx

Dont just copy this code without comprehending it, try and learn how it works. Usually good ways to practice learning a programming language is trying different problems and seeing how you can solve it. I recommend this site, because i used it a lot when i first started programming.

And also, dont just post your homework or stuff like that if you dont know how to do it, only if you get stuck. First try thinking of lots of ways you think you can figure something out, and if you dont know how to do a specific task just look it up and learn from it.

Upvotes: 4

John La Rooy
John La Rooy

Reputation: 304413

Here's a small change you could make to your program

n = 5
for k in range(n):
    for j in range(n):
        print('x' if j+k >= n-1 else ' ', end='')
    print()

It's not a very good way to do it though. You should think about printing a whole like at a time using something like this

n = 5
for k in range(n):
    i = ???
    j = ???
    print(' '*i+'x'*j)

You just need to work out i and j

Upvotes: 0

Related Questions