[英]Why does my loop continue as an infinite loop?
我有一些代碼,但我無法理解為什么循環是無限循環,即使我有一個應該結束循環的 else 條件。
def add1(*args):
total = 0
add = True
for num in args:
while add == True:
if num!=6:
total = total + num
else:
add = False
return total
add1(1,2,3,6,1)
我的問題是,我有一個 else 語句將 add 更改為“False”,因此循環應該停止,但由於某種原因它沒有停止。
但是,如果我對代碼稍作改動,它就會停止:
def add1(*args):
total = 0
add = True
for num in args:
while add == True:
if num!=6:
total = total + num
break
else:
add = False
return total
add1(1,2,3,6,1)
基本上,添加一個休息。 我不明白專業的 Python 編碼人員實際上是如何在他們的腦海中解釋“中斷”的。 我已經閱讀了有關 break 的文章,但似乎仍然不太明白。 我不明白為什么需要“休息”,為什么“其他”還不夠。
當您進入for
循環時, num
獲得值1
( args
的第一個值)。 然后進入while
循環(因為add
為 True)。 現在,因為num
不等於6
,您進入if
塊,所以else
塊不會執行。 然后,您只需返回while
循環,並且num
的值不會改變。 然后,因為num
不等於6
(記住它沒有改變,它仍然是1
),再次進入if
塊,依此類推,直到終止程序。
添加break
,將退出最近的循環,在本例中是while
循環,因此for
循環繼續,直到num
獲得值6
,並且add
變為False
。 發生這種情況時, while
循環將不再執行。
def add1(*args):
total = 0
add = True
for num in args:
if add == True:
if num!=6:
total = total + num
else:
add = False
break #breaking the for loop for better performance only.
return total
add1(1,2,3,6,1)
這會添加到 6 沒有遇到。 您正在不必要地使用 while 循環。 您必須通過某種條件打破無限循環,而該條件是當 num!=6 時。 甚至你的 else 部分也可以打破無限的 while 循環,但在我看來,while 循環本身是不必要的。
我相信您的代碼的目的是將 *args 中的元素匯總到第一次出現數字 6 為止。如果是這種情況,那么這里的 while 循環是多余的。 更改第一個代碼片段:
def add1(*args):
total = 0
for num in args:
if num != 6:
total = total + num
else:
break
return total
add1(1, 2, 3, 6, 1)
在您的原始代碼中實際發生的是num變量在 while 循環中迭代時不會以任何方式改變,因此它永遠不會進入 else 部分,有效地卡在第一個不是 6 的輸入參數上,見下文:
def add1(*args): # [1, 2, 3, 6, 1]
total = 0
add = True
for num in args: # first element is 1. num = 1
while add == True:
if num != 6: # num = 1 always
total = total + num
# adding break here gets out of the while loop on first iteration, changing num = 2
# and later to 3, 6...
else: # else is never reached
add = False
return total
add1(1, 2, 3, 6, 1)
您應該更改以下代碼:
從
if num != 6:
到
if total != 6:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.