while循环不更新

While loop not updating

以前有人问过这个版本,但我不明白,所以我需要用一个简单的测试用例再问一次。有几个函数与我正在编写的实际程序有关,但我试图在一个简单的案例中理解错误。

a = 0

def test(c):
    c = c + 2
    return c
    
def test2():
    ct = 0
    while True:
        print(test(a))
        ct += 1
        if ct > 4:
            break
    
test2()

运行 这将打印“2”五次。为什么不是每次都更新?我如何让它更新?

如果我这样做,也会发生同样的事情:

a = 0

def test(c):
    c = c + 2
    return c
    
def test2():
    d = a
    ct = 0
    while True:
        print(test(d))
        ct += 1
        if ct > 4:
            break
    
test2()

test() returns 循环内 d 的值。所以,我看不到它会在哪里重置为 0。

是因为你没有使用返回的c值

a = 0

def test(c):
    c = c + 2
    return c


def test2():

    global a

    ct = 0
    while True:
        a = test(a)
        print(a)
        ct += 1
        if ct > 4:
            break

test2()

结果

2
4
6
8
10

你永远不会更新 a 所以它每次都会打印相同的值

a = 0
def test(c):
    c = c + 2
    return c
    
def test2():
    ct = 0
    while True:
        print(test(a))# "a" is not updated
        ct += 1
        if ct > 4:
            break
    
test2()

你可以做的是声明变量,a 来保存调用函数 test(a) 的值。此变量保存调用测试函数自身的值,test(a),开始时为 0,然后在每个循环中递增,将变量 a 赋给前一个值加上2. 为 while 循环声明一个布尔变量被认为是更好的做法。尝试使用调试模式尝试下面的代码并继续操作。

def test(b):
    b += 2
    return b

def test2():
    ct = 0
    a = 0
    keep_going = True
    while keep_going:
        a = test(a)
        print(a)
        ct += 1
        if ct > 4:
            keep_going = False

test2()