title: How to interrupt a while loop, run a function and go back to the loop
body: <p>I'm beginning with Python and Raspberry Pi and was trying to make some Physical Computing with them.</p>
  
  <p>I began with that: <a href="https://www.raspberrypi.org/learning/physical-computing-with-python/" rel="nofollow noreferrer">https://www.raspberrypi.org/learning/physical-computing-with-python/</a> and everything went well.</p>
  
  <p>Than I tried to play around with traffic lights (with success!):
  <a href="https://www.raspberrypi.org/learning/physical-computing-with-python/trafficlights/" rel="nofollow noreferrer">https://www.raspberrypi.org/learning/physical-computing-with-python/trafficlights/</a></p>
  
  <p>Here my code:</p>
  
  <pre><code>from gpiozero import Button, TrafficLights
  from time import sleep
  
  lights = TrafficLights(25, 8, 7)
  
  while True:
      lights.green.on()
      print("GREEN")
      sleep(12)
      lights.green.off()
      lights.amber.on()
      print("AMBER")
      sleep(4)
      lights.red.on()
      lights.amber.off()
      print("RED")
      sleep(12)
      lights.amber.on()
      print("RED &amp; AMBER")
      sleep(4)
      lights.red.off()
      lights.amber.off()
  </code></pre>
  
  <p>Than I tried to add a button for a pedestrian crossing. But here I have problems.</p>
  
  <p>Here the code:</p>
  
  <pre><code>from gpiozero import Button, TrafficLights
  from time import sleep
  
  button = Button(21)
  lights = TrafficLights(25, 8, 7)
  
  def pedestrian_crossing():
      sleep(4)
      lights.off()
      lights.amber.on()
      print("Pedestrian crossing: AMBER")
      sleep(4)
      lights.red.on()
      lights.amber.off()
      print("Pedestrian crossing: RED")
      sleep(12)
      lights.amber.on()
      print("Pedestrian crossing: RED &amp; AMBER")
      sleep(4)
      lights.red.off()
      lights.amber.off()
  
  button.when_pressed = pedestrian_crossing
  
  while True:
      lights.green.on()
      print("GREEN")
      sleep(12)
      lights.green.off()
      lights.amber.on()
      print("AMBER")
      sleep(4)
      lights.red.on()
      lights.amber.off()
      print("RED")
      sleep(12)
      lights.amber.on()
      print("RED &amp; AMBER")
      sleep(4)
      lights.red.off()
      lights.amber.off()
  </code></pre>
  
  <p>I tried with <code>button.wait_for_press</code>, <code>button.wait_for_release</code> &amp; Co., but <code>button.is_pressed</code> was the one that gave me the best result.</p>
  
  <p>The problem is that when I press the button, the function is called, but the loop continues. So how could I rewrite the code and than when I press the button the loop stops, the function is called, everything inside the function is done and then it goes back to the loop?</p>
  
  <p>Or there's another solution, with the other button attributes?</p>
  
  <p>Thanks in advance!</p>