While循环未更新

时间:2020-11-04 08:28:58

标签: python while-loop global-variables

以前曾有人问过这个问题的版本,但我不明白,所以我需要用一个简单的测试用例再次询问。具有多个功能与我正在编写的实际程序有关,但是我试图在一个简单的情况下理解故障。

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()返回循环中d的值。因此,我看不到它将重置为0的位置。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您永远不会更新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()

答案 2 :(得分:0)

您可以做的是声明变量 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()
相关问题