Python-如何让print语句打印最大次数
我有下面的代码,它打印我需要的东西,但我需要代码根据def函数执行两次。我相信这很简单,但我一辈子都搞不懂Python-如何让print语句打印最大次数,python,python-3.x,Python,Python 3.x,我有下面的代码,它打印我需要的东西,但我需要代码根据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') 我在运行代码时得到了以下输出: >
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
>>>
只需添加一个for循环
for i in range(max_repeat):
n2=n
while n2 > 0:
print (n2)
n2 = n2-1
if n2 == 0:
print('blast off')
您也可以对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\u 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