如何在python中停止无限循环

man*_*ate 0 python loops infinite-loop while-loop

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

while get_next_value(deck) < 27:
     if get_next_value(deck) < 27:
        result = get_next_value(deck)
return result
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 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
Run Code Online (Sandbox Code Playgroud)

不仅无限递归已停止,而且此方法每次迭代仅运行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
Run Code Online (Sandbox Code Playgroud)

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