(Maybe off topic) Can someone explain what a finite state machine is?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jul 20 03:29:48 EDT 2011

On Tue, 19 Jul 2011 11:32 pm Matty Sarro wrote:

> Hey everyone. I am currently reading through an RFC, and it mentions
> that a client and server half of a transaction are embodied by finite
> state machines. I am reading through the wikipedia article for finite
> state machines, and sadly it's going a bit above my head. I don't
> really have a background in engineering, and would really love to
> understand what is being said. Does anyone have a simple way to
> explain it?

Consider a heater with a thermostat. That's a finite state machine. It's a
machine, it has a finite number of states, namely, the combinations of

"on" or "off"
"too warm", "too cold" or "in-between"

The machine has transitions between states:

"if too warm, then turn off"
"if too cold, then turn on"
"if in-between, then don't change"

Here's one way to simulate such a simple FSM in Python:

import time

class Heater:
    low = 0
    high = 10
    def __init__(self, starting_temperature=7):
        self.temp = starting_temperature
        self.state = "off"
    def run(self):
        while True:
            if self.state == "on":
                # Heating.
                self.temp += 1
            if self.state == "off":
                # Slowly cooling.
                self.temp -= 1
            if self.temp < self.low:
                print("turning on")
                self.state = "on"
            if self.temp > self.high:
                print("turning off")
                self.state = "off"

>>> heater = Heater()
>>> heater.run()
turning on
turning off
turning on
turning off
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in run

More complex finite state machines can have many different states, and much
more complicated behaviour.


More information about the Python-list mailing list