简体   繁体   English

如何在第一次迭代中仅打印一次递归 Python function 中的语句?

[英]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.

相关问题 如何修复我的递归倒计时 python 函数的代码,以便它只打印“LIFT OFF!” 一次? - How do I fix my code for my recursive countdown python function so that it only prints “LIFT OFF!’ once? 如何只打印一次递归调用中的语句? Python - How to print the statement only once which is inside recursion call? Python 为什么我必须在 python 中添加三次打印 function 我只需要打印一次即可获得 output - Why do I have to add print function thrice in python i need to give print only once to get the output 如何在 python3 中的不同行上打印每个迭代? - How do I print each iteration on separate lines in python3? 如何在 Python 中打印出 for 循环的每次迭代? - How do I print out each iteration of the for loop in Python? 仅当它们在 python 的列表中出现多次时,我如何打印值 - How do I print values only when they appear more than once in a list in python 如何在for循环中只打印一次语句 - How to print statement only once inside a for loop 如何在循环中只打印一次语句 - How to print out a statement only once in loop Python:如何在运行for语句后不仅输出最终值,还输出中间输出? - Python:How do I print not only the final value after running the for statement, but also the middle output? 如何使用 Python 仅打印文本文件中字符串的第一个实例? - How do I print only the first instance of a string in a text file using Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM