我有一些代码,我很难理解为什么循环是一个无限循环,即使我有一个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
是真的)。现在,因为num
不等于6
,所以输入if
块,所以else
块不会执行。然后,返回到while
循环,num
的值不会改变。然后,因为num
不等于6
(记住它没有改变,它仍然是1
),再次输入if
块,依此类推,直到终止程序。你知道吗添加
break
时,退出最近的循环,在本例中是while
循环,因此for
循环继续,直到num
获得值6
,add
成为False
。当这种情况发生时,while
循环将不再执行。你知道吗这加起来直到没有遇到6为止。不必要地使用while循环。你必须用某个条件来打破无限循环,这个条件就是num!=6. 即使你的else部分也可以打破无限while循环,但是根据我的说法while循环本身是不必要的。你知道吗
我相信您的代码的目的是将*args中的元素汇总到第6个数字的第一次出现。如果是这样的话,while循环在这里是多余的。更改第一个代码段:
在原始代码中实际发生的情况是,在while循环中迭代时,num变量不会以任何方式更改,因此它永远不会进入else部分,实际上会被卡在不是6的第一个输入参数上,请参见以下内容:
相关问题 更多 >
编程相关推荐