【问题标题】:Python - How to get print statement to print max number of timesPython - 如何让打印语句打印最大次数
【发布时间】:2017-06-16 10:37:08
【问题描述】:

我有下面的代码,它会打印我需要的内容,但我需要代码根据 def 函数执行两次。我敢肯定这很简单,但我一辈子都想不通

def countdownWhile(n, max_repeat):
    # display countdown from n to 1
    while n > 0:
        print (n)
        n = n-1
        if n == 0:

            print('blast off')

我在运行代码时得到以下输出:

>>> countdownWhile(5,2)
5
4
3
2
1
blast off
>>> 

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    只需添加一个 for 循环

    for i in range(max_repeat):
    
        n2=n
    
        while n2 > 0:
    
            print (n2)
    
            n2 = n2-1
    
            if n2 == 0:
    
                print('blast off')
    

    【讨论】:

      【解决方案2】:

      您也可以对 max_repeat 参数使用循环。

      def countdownWhile(n, max_repeat):
          # display countdown from n to 1
          while max_repeat > 0:
               while n > 0:
                   print (n)
                   n = n-1
                   if n == 0:
                       print('blast off')
               max_repeat -= 1
      

      这将打印倒计时max_repeat 次数。

      【讨论】:

        【解决方案3】:
        def countdownWhile(n, max_repeat):
            for i in range(max_repeat):
                for x in range(n,0,-1):
                    print (x)
            print('blast off')
        

        运行

        In [6]: countdownWhile(5,2)
        5
        4
        3
        2
        1
        5
        4
        3
        2
        1
        blast off
        

        【讨论】: