Simon Erasmus Simon Erasmus - 2 months ago 6
Python Question

if statement value not changing in loop if called from another function in python

there. I was creating a program and ran into a problem that baffles me and my understanding of basic code (or my understanding of my eyesight).

According to me this code should print out


Test


immediately as the program starts and then when ext() is called from Timer thread the loop variable will change to False, essentially returning false on the if statement and not continuing to print out 'Test'.

But even though ext() is called(I tested this) the if statement gets on being called and loop does not change to False.

from threading import Timer, Thread
from time import sleep

loop = True

def hello():
while True:
if loop == True:
print('Test')
sleep(0.5)

def ext():
loop = False

th = Thread(target=hello)
th.start()

t = Timer(5, ext())
t.start()


Please help as I have been stuck for this for several hours.

Answer

You need to specify loop as a global variable. In ext() it thinks that you are defining a new variable called loop while you actually want to modify the global variable. So the correct code would be this one:

from threading import Timer, Thread
from time import sleep

loop = True

def hello():
    while True:
        if loop == True:
            print('Test')
            sleep(0.5)

def ext():
    global loop
    loop = False

th = Thread(target=hello)
th.start()

t = Timer(5, ext)
t.start()

You also need to change the one before last line and instead of calling ext pass it to Timer