Skip to main content
 首页 » 编程设计

Python:在无限循环函数中只运行一次代码段..

2025年05月04日34daizhj

我有一个反复运行的函数。在该函数内部,我希望特定的段仅在该函数第一次运行时运行。

我不能使用函数外部的任何变量,例如

    firstTime = True 
 
    myFunction(firstTime): #function is inside a loop 
        if firstTime == True: 
            #code I want to run only once 
            firstTime = False 
        #code I want to be run over and over again 

我也不想使用全局变量。

有什么想法可以实现吗?

请您参考如下方法:

使用可变的默认参数:

>>> def Foo(firstTime = []): 
    if firstTime == []: 
        print('HEY!') 
        firstTime.append('Not Empty') 
    else: 
        print('NICE TRY!') 
 
 
>>> Foo() 
HEY! 
>>> Foo() 
NICE TRY! 
>>> Foo() 
NICE TRY! 

为什么会这样?检查this询问更多详情。