The Halting Problem

Let's assume that it is possible to write a Python program that correctly tells whether other Python programs will eventually halt when given particular inputs. Let's call our hypothetical program halts. Here's a rough sketch of what it would look like:

def halts(program, data):

   ... lots of complicated code ...

   if ... some condition ...:
      return True
   else:
      return False

Halts takes two inputs, called program and data. The first input is an arbitrary Python program, and the second input represents the data to feed to that program as input. Halts returns either True or False, depending on whether program ever halts when given data as input. For example, let's write a couple of simple Python programs to test halts with:

def progA(input):
  print 'done'

def progB(input):
  if input == 1:
    while True: pass   # this causes an infinite loop
  else:
    print 'done'

Now we can ask halts what these programs do when given various inputs. ProgA always halts, no matter what input we give it:

ProgB loops forever if we happen to feed it the value 1. Any other value will cause it to halt:

So far, we have every reason to believe that halts could exist, at least in principle, even though it might be a rather complicated program to write. At this point, Turing says "OH YEAH? If halts exists, then I can define the following program called turing which accepts any Python program as input..."

def turing(program):
  if halts(program, program):
    while True: pass
  else:
    print 'done'

At this point, we say "Yes, so what?" Turing laughs and says "Well, what happens when I feed the turing program to itself?"

turing(turing)

What happens indeed? Let's analyze the situation:

Thus our original assumption about the existence of halts must have been invalid, since as we just saw, it's easy to define the logically-impossible turing program if halts is available to us.

Q.E.D.

Conclusion

The task of deciding if an arbitrary computation will
ever terminate cannot be described computationally