Python如何获取print语句的最大打印次数

2024-04-25 16:38:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,它打印我需要的,但我需要的代码执行两次基于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
>>> 

Tags: to函数代码fromdefdisplaymaxrepeat
3条回答

只需添加一个for循环

for i in range(max_repeat):

    n2=n

    while n2 > 0:

        print (n2)

        n2 = n2-1

        if n2 == 0:

            print('blast off')

您也可以使用max\u 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次。你知道吗

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

相关问题 更多 >