繁体   English   中英

为什么我的循环继续无限循环?

[英]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获得值1args的第一个值)。 然后进入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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM