为什么我的循环是无限循环?

2024-09-30 02:31:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码,我很难理解为什么循环是一个无限循环,即使我有一个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”的。我读过关于休息的文章,但似乎还是不能很好地理解。 我不明白为什么“休息”是必要的,为什么“其他”是不够的。你知道吗


Tags: 代码inaddfalsetrueforreturnif
3条回答

当您进入for循环时,num获得值1(在args中的第一个值)。然后进入while循环(因为add是真的)。现在,因为num不等于6,所以输入if块,所以else块不会执行。然后,返回到while循环,num的值不会改变。然后,因为num不等于6(记住它没有改变,它仍然是1),再次输入if块,依此类推,直到终止程序。你知道吗

添加break时,退出最近的循环,在本例中是while循环,因此for循环继续,直到num获得值6add成为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)

在原始代码中实际发生的情况是,在while循环中迭代时,num变量不会以任何方式更改,因此它永远不会进入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)

相关问题 更多 >

    热门问题