簡體   English   中英

If 語句在 While True 循環中返回 False (Python)

[英]If statement returning False in While True loop (Python)

我希望在這個 If 語句中,變量 'i' 會遞增,直到它最終等於 10,隨后 'if 10 < 10' 將返回 False,從而打破我的 while 循環。 但是這段代碼似乎打印到 10 點,然后陷入無限循環,除非我添加 else:break。 為什么?

i=0
while True:
    if i < 10:
        i = i + 1 
        print(i)

while True將使循環永遠運行,因為“true”總是評估為 true。 您可以通過中斷退出循環。

為了實現你想做的事情,我會使用

while i < 10:
    print (i)
    i++

X等於Truewhile X重復,所以在while True中它總是True 它只用break語句中斷。 在您的代碼中,您僅使用 if 檢查while循環內的值,因此您既不會中斷 while 循環,也不會在while True中將True更改為False

如果你想使用while

i = 0
while i < 10:
    i += 1
    print(i)

或者

i = 0
while True:
    if i < 10:
        i += 1
        print(i)
    else:
        break

沒有while

for i in range(10):
    print(i)

那是因為沒有任何東西告訴你終止循環。 所以即使在 if 語句不滿足之后它也會繼續。

這就是為什么while True時使用通常不是一個好習慣的原因

當 break 條件內置到循環中時,您可以使用 for 循環實現相同的目的:

for i in range(0, 10):
    print(i)

如果你想使用 while True 那么你可以 go 用於:

i=0
while True:
   i = i + 1 
   print(i)
   if i == 10:
      break

我認為您需要在這里了解一些事情,因為您設置了while True這意味着語句永遠不會為false ,因此即使if condition失敗, while loop也永遠不會結束。 因此, while loop將繼續運行,直到您中斷。

你可以在沒有中斷的情況下實現這一點的唯一方法是這樣的,你有一個變量,當if loop失敗時,它會將while loop的條件重置為 false

i=0
condition = True
while condition:
    if i<10:
        i=i+1
        print(i)
    else:
        condition=False

暫無
暫無

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

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