Reading about Python? Actually practice it. Try PyChallenge free

Python Tutorial

Python finite state machine

Introduction

A finite state machine (FSM) is a mathematical model of computation with states, transitions, inputs and outputs. This machine is always in a one state at the time and can move to other states using transitions. A transition changes the state of the machine to another state.

A large number of problems can be modeled using finite state machines. Simple examples of state machines used in modern life are vending machines, elevators and traffic lights.  Advanced usage are artificial intelligence, language parsing and communication protocol design.

Related course
Practice Python with interactive exercises

Finite State Machine Example

First install the Fysom module:
sudo pip install fysom
We can define a Finite State Machine (FSM) with two states: sleeping and awake.  To move between the states we will define the transitions wakeup() and sleep().

finite state machine Finite state machine. States: awake, sleeping. Transitions: sleep, wake up

Example:

from fysom import *

fsm = Fysom({'initial': 'awake', 'final': 'red', 'events': [ {'name': 'wakeup', 'src': 'sleeping', 'dst': 'awake'}, {'name': 'sleep', 'src': 'awake', 'dst': 'sleeping'}]})

print(fsm.current) # awake fsm.sleep() print(fsm.current) # sleeping fsm.wakeup() print(fsm.current) # awake

Result:

awake
sleeping
awake

Finite State Machines

There are several implementations of Finite State Machines in Python:
Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser — no install needed.
Practice Python with interactive exercises