== Introduction == This main purpose of this part of the recipe is to exhibit a simple state machine that accepts a five-digit American zip code. The approach indicated in this recipe might be alright for testing a particular state machine against actual input strings. Unit testing would be better. == What Objects are Involved == No notable Python or wxPython classes or modules are employed in this code. == Process Overview == The state machine defined in this recipe accepts only strings consisting of exactly five digits. There are only two states, and only one of these is of any size at all. The main thing to notice is that the state defined by `local` raises a special exception when it encounters an unnacceptable character. I suspect that, in most cases, this might be the only type of exception that will need to be raised in state machines meant for use in validators. Notice too that the state machine is defined only once but that the function `display` redefines the sequence of input tokens for the state machine, once for each string that the function processes. Convenience code in the state machine converts state machine exceptions into various result values that can be readily processed by a validator. == Special Concerns == I should have used real unit testing in this code, eh. == Code Sample == {{{ #!python from StateMachine import EBadCharacter, BADCHARACTER, STRINGTOOLONG, OK, StateMachine def local ( self, token ) : for c in range ( 5 ) : if not token . isdigit ( ) : raise EBadCharacter ( ) if c < 4 : token = self . nextToken ( ) return 'complete', None def complete ( self, token ) : pass statemachine = StateMachine ( ) statemachine . addState ( local ) statemachine . addState ( complete, True ) statemachine . setStartState ( local ) if __name__ == "__main__" : def display ( input ) : statemachine . allTokens = [ ] print input, result = statemachine . testString ( input ) print result, if result . rejectCharacter ( ) : print 'reject last character, ', else : print 'accept last character, ', if result . validatedString ( ) : print 'validated string ', print " [accumulator: %s]" % '' . join ( statemachine . allTokens ) else : print 'not validated' display ( '22' ) display ( '22x' ) display ( '2291' ) display ( '229x' ) display ( '22999' ) }}} === Comments === I welcome your comments. - [[Bill Bell]]