[英]How do I print a statement in a recursive Python function only once in the first iteration?
I need to write a function that prints a timer as output (everything at the same time).我需要编写一个 function 打印一个计时器为 output (同时一切)。 However, I need to write "Ready?"但是,我需要写“准备好了吗?” at the beginning, so I only want it to be printed once.一开始,所以我只希望它打印一次。
Here's what I have so far:这是我到目前为止所拥有的:
def factorial(i):
while i > 0:
print(i)
return (factorial(i-1))
print('Go!')
factorial(5)
I want the function to print the output like so:我希望 function 像这样打印 output :
Ready?
5
4
3
2
1
Go!
You can use an inner function :您可以使用 内部 function :
def factorial(i):
def recursive_output(i):
if i > 0:
print(i)
recursive_output(i-1)
print("Ready!")
recursive_output(i)
print("Go!")
You can add an argument to the function您可以向 function 添加参数
FIRST_TIME = True
NOT_FIRST_TIME = False
def factorial(i, is_first_time):
if is_first_time:
print('Ready?')
if i:
print(i)
return (factorial(i-1, NOT_FIRST_TIME))
print('Go!')
factorial(5, FIRST_TIME)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.