if statement value not changing in loop if called from another function in python
<p>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).</p>

<p>According to me this code should print out</p>

<blockquote>
  <p>Test</p>
</blockquote>

<p>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'.</p>

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

<pre><code>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()
</code></pre>

<p>Please help as I have been stuck for this for several hours.</p>

<p>You have two problems... well, three really. First, <code>ext</code> is referencing a local variable called <code>loop</code> not the global. Second, you don't really start the thread because you called the function instead of passing in its reference. Third... you no longer sleep when <code>loop</code> is set so your code ends up eating a full cpu in a tight loop. Fixing the first two would be</p>

<pre><code>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()
</code></pre>

python if-statement timer definition