title: Interrupting a for loop while receiving data from a serial port
body: <p>How can I make my program interrupt an already running for loop when it receives the "K" character from a serial port ? </p>
  
  <p>The code is :</p>
  
  <pre><code>import serial
  from time import sleep
  
  ser = serial.Serial(port='/dev/ttyUSB0',baudrate=9600,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=0)
  
  while 1:
      for line in ser.read(1):
          input+=chr(line)
  
          if input == 'S':
              for x in range (1 , 10):  # this is the loop i want to break
                  print(x)
                  sleep(1)
  
          if input == 'K':
              print('K received -&gt; BREAK')
              break
  
          print("Finished")
  </code></pre>
  
  <p>That way the program prints 'K received -> BREAK' after the for loop finished.</p>