Search code examples
pythonwhile-loopglobal-variables

While loop not updating


Versions of this have been asked before but I don't get it, so I need to ask again with a simple test case. Having several functions is relevant to the actual program I'm writing, but I'm trying to understand the fault on a simple case.

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()

Running this prints '2' five times. Why wouldn't it update each time? How would I get it to update?

The same thing happens if I do something like this:

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 a value for d which is within the loop. So, I can't see where it would get reset back to 0.


Solution

  • What you can do is declare the variable, a to hold the value of calling the function test(a). This variable holds the value of calling the test function on itself, test(a), which to begin with is 0, then increments through each loop, assigning the variable a to the previous value plus 2. Declaring a Boolean variable for the while loop is considered better practise. Try play around with the code below using debug mode and follow along.

    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()