Search code examples
pythonstate-machineexit-code

how to define a final state in a state machine with python


I have this state machine:

class Chat(StateMachine):

    begin= State('begin', initial=True)
    state1=State('State1')
    state2=State('State2')

    go_to_state1=begin.to(state1)
    go_to_state2=state1.to(state2)

    def on_enter_begin(self):
        global name
        name = input("Please enter your name:\n")
        self.go_to_state1()

    def on_enter_state1(self):
        global name
        print("first state ")
        value = input("hi "+name)

        if value=="quit":
            print('see you soon!')
            break
        else :
            self.go_to_state2()
chat=Chat()
chat.on_enter_begin()

but I got this: break ^ SyntaxError: 'break' outside loop


Is there a way to define the final state? something like if the user types "quit" the state machine exit/break ??


Solution

  • Yes, you have to use return instead of break as you are not within a loop:

    if value=="quit":
        print('see you soon!')
        return True