How to Interrupt a Program in Python - dummies

How to Interrupt a Program in Python

By Brendan Scott

Usually you get called rude if you interrupt. Not in programming. Are you ready to create a program that never finishes by itself (called an infinite loop)? This section shows you how to force it to stop.

Forcing a stop is useful when your program locks up and won’t respond. The trick is to press Ctrl+C (the Ctrl key and the C key at the same time; dont press the Shift key). Make sure the Python window is active (by clicking the window) when you do — or you might close the wrong program!

Here’s how you write an infinite loop program:

  1. Type while True: and press Enter.

  2. Press the spacebar four times.

  3. Type pass.

  4. Press Enter twice.

This is what you’ll see:

>>> while True:
… pass
…

The Python interpreter is unresponsive. If you try to get it to assign or print something, nothing happens. It lays there like a lump. The usual >>> prompt isn’t there. You may also hear your computer laboring.

Quick: Press Ctrl+C to break out of the loop and get control back. You get this when you do it:

>>> while True:
…       pass
…
^CTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>>