[英]How to stop an infinite loop in python
这是重复执行的函数(调用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
它应该这样写:
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
这两种解决方案基本上都做相同的事情,因此它们之间的选择只是一种选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.