簡體   English   中英

如何在循環時退出此操作?

[英]How do I exit this while loop?

我在退出以下循環時遇到問題。 這是一個簡單的程序,如果隨機值大於5,則打印hello 。程序運行良好一次但是當我嘗試再次運行它時會進入無限循環。

    from random import *

    seed()
    a = randint(0,10)
    b = randint(0,10)
    c = randint(0,10)
    count = 0

    while True:
        if a > 5 :
           print ("aHello")
           count = count + 1
        else : 
           a = randint(0,10)
        if b > 5 : 
           print ("bHello")
           count = count + 1
        else :
           b = randint(0,10)
       if c > 5 :
           print ("cHello")
           count = count + 1
       else :
           c = randint(0,10)

      if count == 20 :
           count = 0
           break

  count = 0

您的while循環可能會將變量計數增加0,1,2或3.這可能會導致計數從低於20的值變為超過20的值。

例如,如果count的值為18,則會發生以下情況:

a > 5, count += 1
b > 5, count += 1
c > 5, count += 1

在這些操作之后,count的值將是18 + 3 = 21,而不是20.因此,將永遠不會滿足條件值== 20。

要修復錯誤,您可以替換該行

if count == 20

if count >= 20

或者只是在while循環中更改程序邏輯。

因為你在一次迭代中增加2或3次count ,它可能會跳過你的count == 20檢查

這是獲得正好20行的一種方法。

from random import seed, randint

seed()
a = randint(0,10)
b = randint(0,10)
c = randint(0,10)
count = iter(range(20))

while True:
    try:
        if a > 5:
            next(count)
            print ("aHello")
        else: 
            a = randint(0,10)
        if b > 5: 
            next(count)
            print ("bHello")
        else:
           b = randint(0,10)
        if c > 5:
            next(count)
            print ("cHello")
        else:
            c = randint(0,10)
    except StopIteration:
        break

請注意,此代碼中仍有很多重復。 將a,b,c變量存儲在list而不是單獨的變量中將允許進一​​步簡化代碼

如果變量abc兩個或多個值大於5,則“中斷”條件可能會失敗。在這種情況下,計數將遞增多次並且計數將結束> 20,並且循環永遠不會終止。 你應該改變:

  if count == 20 :

  if count >= 20:

在迭代結束時,由於多個增量, count可能大於20 所以我會將最后一個if語句更新為:

if count >= 20:

感到安全

如果你的目標是當count >= 20時停止計數,那么你應該將這個條件用於你的while循環而你根本不需要打破,因為你只需要在循環結束時中斷。

新的while語句看起來像

while count < 20:
    # increment count

然后在while循環之外,如果你想再次使用它,你可以將count重置為0

以下代碼有幫助嗎?

while True:
    if a > 5 :
       print ("aHello")
       count = count + 1
       if count == 20 :
            break
    else : 
       a = randint(0,10)
    if b > 5 : 
       print ("bHello")
       count = count + 1
       if count == 20 :
            break
    else :
       b = randint(0,10)
   if c > 5 :
       print ("cHello")
       count = count + 1
       if count == 20 :
            break
  else :
       c = randint(0,10)

每次遞增后都必須檢查計數值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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