【问题标题】:How to stop an infinite loop in python如何在python中停止无限循环
【发布时间】:2013-11-19 10:16:05
【问题描述】:

这是重复的函数(调用 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

【问题讨论】:

    标签: python loops while-loop infinite-loop


    【解决方案1】:

    应该这样写:

    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)一次,而不是3次。

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

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多