[英]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
等於True
時while 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.