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

2019-10-02 09:21发布

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()

4条回答
SAY GOODBYE
2楼-- · 2019-10-02 09:44

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

查看更多
Evening l夕情丶
3楼-- · 2019-10-02 09:44

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:

* * * * * * * * *
   * * * * * * *
     * * * * *
       * * * 
         *
查看更多
你好瞎i
4楼-- · 2019-10-02 09:51
hight = 5
for star in range(hight):
    for num in range(hight):
        print('*' if num+star >= hight-1 else ' ', end='')
    print()
查看更多
你好瞎i
5楼-- · 2019-10-02 09:59

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.

查看更多
登录 后发表回答