【问题标题】:How to print triangle using '*' in Python? [closed]如何在 Python 中使用“*”打印三角形? [关闭]
【发布时间】:2019-02-09 05:22:06
【问题描述】:

喜欢:

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

注意:其中 n 将用户输入奇数。

【问题讨论】:

    标签: python numbers integer


    【解决方案1】:

    遍历从0n / 2 的行号,然后将行号的两倍加一星居中。

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

    给出:

        *     
      * * *   
    * * * * * 
    

    【讨论】:

      【解决方案2】:
      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)  
      

      输出:

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

      【讨论】:

      • 这是问题的答案或问题的附加信息?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多