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 need to specify <code>loop</code> as a global variable. In <code>ext()</code> it thinks that you are defining a new variable called <code>loop</code> while you actually want to modify the global variable. So the correct code would be this one:</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>

<p>You also need to change the one before last line and instead of calling <code>ext</code> pass it to <code>Timer</code></p>

python if-statement timer definition