如何在Python中使用'*'打印三角形?

时间:2018-09-04 08:19:18

标签: python numbers integer

赞:

          *
        * * *
      * * * * *
      ----n=5----

注意:n表示用户输入的是奇数整数。

2 个答案:

答案 0 :(得分:2)

将行号从0迭代到n / 2的上限,然后将行号居中两倍,再加上一颗星。

n = 5
for l in range(n//2+1):
    print(' '.join(['*'] * (l*2+1)).center(n*2))

给出:

    *     
  * * *   
* * * * * 

答案 1 :(得分:1)

def asterisk_triangle(n):
    """
    takes an integer n and then returns an
    asterisk triangle consisting of (n) many columns
    """
    x = 1
    while (x <= (n+1)/2):
        space = int((n+1)/2-x)
        print(" " *space*2, end='')
        print("* " * (2*x-1))
        x = x + 1

    return

# call asterisk_triangle function here
# here n=9
asterisk_triangle(9)  

输出:

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