Working around a lack of 'goto' in python

Roy Smith roy at
Sun Mar 7 19:54:33 CET 2004

Stephen Horne <steve at> wrote:

> a goto is the natural representation of a transition between states.

Except that a goto allows the code for a state to be fallen into from 
the top.

The best way I know to implement a state machine in Python is one 
function for each state, and have each function return the next state, 
or perhaps an (output, nextState) tuple.  Your main loop then becomes 
something like:

   state = start
   while state != end:
      nextState, output = state (input)
      print output
      state = nextState
I would use a similar strategy in a language like C or C++ which allowed 
you to pass function pointers around.

I've implemented state machines in Perl with a huge multi-way 
if/elif/elif/else statement.  It's pretty ugly, but it beats gotos.

More information about the Python-list mailing list