Skip to main contentMercury Labs

What is a Finite State Machine?

Archie Norman
Archie Norman
Explore an example of a finite state machine and delve into the technical elements involved.

Welcome to our technical blog post on finite state machines!

Simply put, a finite state machine is a mathematical model of computation used to design algorithms and computer programs. It consists of a finite number of states, transitions between those states, and actions.

Here's a quick example to illustrate how a finite state machine works. Let's say we have a vending machine that dispenses drinks. The states of the machine could be "waiting for input," "dispensing drink," and "out of stock." Events, such as a customer inserting money or pressing a button to select a particular drink would trigger transitions between states. And the actions associated with each state might include displaying a message on the screen or releasing a drink.

But enough abstract concepts - let's see some code! Here's an example of a finite state machine implemented in Python:


class VendingMachine:
  def __init__(self):
    self.state = "waiting for input"
    self.stock = {"Coke": 10, "Sprite": 5, "Pepsi": 7}

  def insert_money(self, amount):
    if self.state == "waiting for input":
      self.state = "dispensing drink"
      self.dispense_drink()
    else:
      print("Sorry, you can't insert money right now.")

  def dispense_drink(self):
    if self.state == "dispensing drink":
      choice = input("What drink would you like? ")
      if choice in self.stock and self.stock[choice] > 0:
        print("Here's your {}!".format(choice))
        self.stock[choice] -= 1
        self.state = "waiting for input"
      else:
        print("Sorry, we're out of that drink.")
        self.state = "out of stock"
    else:
      print("Sorry, the machine can't dispense a drink right now.")

vending_machine = VendingMachine()

# The vending machine is waiting for input.
vending_machine.insert_money(5)
# Output: "What soda would you like? Coke"
# Output: "Here's your Coke!"

# The vending machine is waiting for input again.
vending_machine.insert_money(2)
# Output: "What soda would you like? Sprite"
# Output: "Here's your Sprite!"

# The vending machine is out of Sprite.
vending_machine.insert_money(2)
# Output: "What soda would you like? Sprite"
# Output: "Sorry, we're out of that drink."

# The vending machine is out of stock.
vending_machine.insert_money(2)
# Output: "Sorry, you can't insert money right now."

We hope this example helps you understand how finite state machines work and how they can be implemented in code. Just remember: when in doubt, turn to a finite state machine to help you design your next computer program.