title: Stop While Loop mid execution in python
body: <p>I am trying to stop a while loop mid execution, if I reverse the value of 'runWhile' mid execution it simply waits until it's over.</p>
  <p><em>Problem:</em> I need it to stop <strong>immediately</strong> whenever I press f10 on the keyboard.</p>
  <pre><code>from pynput import keyboard
  import threading
  import datetime, time
  
  def exec():
      while runWhile:
          print(&quot;There I go&quot;)
          time.sleep(3)
          print(&quot;I overtaken&quot;)
          time.sleep(3)
          print(&quot;You cant stop me until I finish&quot;)
          
  def on_press(key):
      global runWhile # inform function to assign (`=`) to external/global `running` instead of creating local `running`
  
      if key == keyboard.Key.f5:
          runWhile = True
          t = threading.Thread(target=exec)
          t.start()
      if key == keyboard.Key.f10:
          # to stop loop in thread
          print(&quot;loading STOPPED&quot;, datetime.datetime.now()) #, end='\r')
          runWhile = False
  
      if key == keyboard.Key.f11:
          # stop listener
          print(&quot;listener TERMINATED&quot;, datetime.datetime.now()) #, end='\r')
          return False
          
          
  #--- main ---
  with keyboard.Listener(on_press=on_press) as listener:
      listener.join()
  </code></pre>
  <p><a href="https://pynput.readthedocs.io/en/latest/keyboard.html" rel="nofollow noreferrer">Im using pynput, docs here</a></p>
  <p><a href="https://stackoverflow.com/questions/66196634/loop-until-key-is-pressed-and-repeat/66199118#66199118"><code>based on @furas code</code></a></p>