如何在python中停止无限循环

时间:2013-11-07 16:37:59

标签: python loops while-loop infinite-loop

这是重复的函数(调用get_next_value获取潜在值!)直到a 生成有效值(1-26范围内的数字).Get_next_value只是一个函数。但它创造了一个无限循环,我将如何解决它?

while get_next_value(deck) < 27:
     if get_next_value(deck) < 27:
        result = get_next_value(deck)
return result

1 个答案:

答案 0 :(得分:11)

这是应该写的:

while True:                        # Loop continuously
    result = get_next_value(deck)  # Get the function's return value
    if result < 27:                # If it is less than 27...
        return result              # ...return the value and exit the function

不仅无限递归已停止,而且此方法每次迭代只运行get_next_value(deck) 一次,而不是三次。

请注意,您也可以这样做:

result = get_next_value(deck)      # Get the function's return value
while result >= 27:                # While it is not less than 27...
    result = get_next_value(deck)  # ...get a new one.
return result                      # Return the value and exit the function

这两个解决方案基本上做同样的事情,所以它们之间的选择只是风格上的一个。