如何在python中制作x的三角形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13908618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:55:30  来源:igfitidea点击:

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

pythonfunctiongeometry

提问by JustaGuy313

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 namount of x's

假设函数是def triangle(n),底行会有nx 的数量

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

采纳答案by Hymancogdill

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

输出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.

而且,如果你不知道怎么做,不要只是发布你的家庭作业或类似的东西,只有当你被卡住时。首先尝试想出很多你认为可以解决问题的方法,如果你不知道如何完成特定任务,只需查看它并从中学习。

回答by John La Rooy

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 iand j

你只需要锻炼ij

回答by Anonymous User

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

回答by Ashish Gupta

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:

输出:

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