我有一个目前正在处理的python程序,除了我遇到“递归深度”问题以及我不知道如何重新编写程序以避免这种情况之外,它工作得非常好。
我的程序基本上就是这样的:
def foo()
x = 0 #
while x != 1:
x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
time.sleep(0.5)
bar = ser.readline() # input from serial source
if len(bar) != 10:
foo()
''' it continues checking "bar" using some more if statement. Finally when the
logic is satisfied the program outputs something but still restarts foo() as
I need the program to run endlessly but I am not sure how to fix the recursive
nature of the program'''
if bar = 1234567890:
print "yay you win"
foo()
#start
foo()
最终我的程序按原样工作,但最终会因递归限制错误而崩溃,所以不理想,因为我需要这个程序无休止地运行但是作为编程的全新内容我不确定如何解决它。我确实尝试将我的程序分成两个或三个单独的函数,而不仅仅是一个,但它仍然表现出递归问题。
感谢您的任何意见。如果有人需要更多的代码,我可以发布它,但认为小块应该足以看到我要去的地方。任何帮助将不胜感激。
答案 0 :(得分:1)
我会尝试这个,因为它在相同的递归级别重复调用函数:
def foo()
x = 0 #
while arming != 1:
x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
time.sleep(0.5)
bar = ser.readline() # input from serial source
if len(bar) != 10:
''' it continues checking "bar" using some more if statement. Finally when the
logic is satisfied the program outputs something but still restarts foo() as
I need the program to run endlessly but I am not sure how to fix the recursive
nature of the program'''
if bar = 1234567890:
print "yay you win"
#start
while 1:
foo()
答案 1 :(得分:1)
foo内部只使用如下的循环:
while True:
x = 0 #
while arming != 1:
x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
time.sleep(0.5)
bar = ser.readline() # input from serial source
if len(bar) != 10:
# do whatever you want but don't call foo
您不需要递归调用foo以使程序继续运行。 True会照顾到这一点。