簡體   English   中英

如何在python中停止無限循環

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM