How do you code a vending machine in Python?


In this article, we will learn to code a vending machine in Python.

Vending Machine with Python

Each item will have its product id, product name, and product cost properties stored in a dictionary. a list that is currently empty but will later be filled with all the selected items.

The value of a "run" variable is True up until the point at which the user decides they are satisfied and do not wish to buy any more products; at that point, the value is changed to False, and the loop ends.

We will now try to understand the Python code for the vending machine.

items_data = [
   {
      "itemId": 0,
      "itemName": "Dairymilk",
      'itemCost': 120,
   },{
      "itemId": 1,
      "itemName": "5star",
      'itemCost': 30,
   },{
      "itemId": 2,
      "itemName": "perk",
      'itemCost': 50,
   },{
      "itemId": 3,
      "itemName": "Burger",
      'itemCost': 200,
   },{
      "itemId": 4,
      "itemName": "Pizza",
      'itemCost': 300,
   },
]

item = []

bill = """
\t\tPRODUCT -- COST
"""
sum = 0
run = True

Printing Menu

A simple and direct loop is written to print the menu for the vending machine along with each item's necessary properties

print("------- Vending Machine Program with Python-------\n\n")
print("----------Items Data----------\n\n")

for item in items_data:
   print(f"Item: {item['itemName']} --- Cost: {item['itemCost']} --- Item ID: {item['itemId']}")

Calculating Total Price

A function called sum() is created, and it iterates over the list of all the chosen items for purchase. After executing a loop over the list and adding the property of product_cost to the total, the function will then return the total amount.

def sumItem(item):
   sumItems = 0
   for i in item:
      sumItems += i["itemPrice"]
   return sumItems

The logic of Vending Machine

Machine(), the primary function of the Python program, is written in the vending machine. The three parameters this function will accept are the items_data dictionary, the run variable with a boolean value, and the item list, which includes all the items the user desires. A while loop is used, however, it only functions when the run variable's value is True.

The product id of the desired item must be entered here. If the product id is less than the total length of items_data dictionary, the entire set of id properties must be added to the list of the item; otherwise, the message "Wrong Product ID" will be printed. If the user declines, the run variable will change to False and they will be prompted to add more items. A prompt will ask if you want to print the entire bill or just the total sum.

def vendingMachine(items_data, run, item):
   while run:
      buyItem = int(
         input("\n\nEnter the item code for the item you want to buy: "))
      if buyItem < len(items_data):
         item.append(items_data[buyItem])
      else:
         print("THE PRODUCT ID IS WRONG!")
      moreItems = str(
         input("type any key to add more things, and type q to stop:  "))
      if moreItems == "q":
         run = False
   receiptValue = int(
      input(("1. Print the bill? 2. Only print the total sum: ")))
   if receiptValue == 1:
      print(createReceipt(item, reciept))
   elif receiptValue == 2:
      print(sumItem(item))
   else:
      print("INVALID")

Function for Creating Bill

The creation of a bill display on the console is another feature of Vending Machine with Python. The function create_bill() will accept two arguments −

  • the item list of the chosen products

  • the bill, which is a string of boilerplate menus, and that has been chosen.

The item's name and price are selected as it iterates over the item list, and the necessary information is printed. Finally, this code will once again output the entire cost using the previous sum() function.

Remember that this create_bill() method was created independently outside of the sum() function.

def create_bill(item, bill):

   for i in item:
      bill += f"""
      \t{i["itemName"]} -- {i['itemCost']}
      """

   bill += f"""
      \tTotal Sum --- {sum(item)}        
        
      """
   return bill

Complete Code of Python Vending Machine

Example

Below is the complete code of above all the steps of creating a vending machine with python −

items_data = [
   {
      "itemId": 0,
      "itemName": "Dairy Milk",
      'itemPrice': 120,
   },{
      "itemId": 1,
      "itemName": "5Star",
      'itemPrice': 30,
   },{
      "itemId": 2,
      "itemName": "perk",
      'itemPrice': 50,
   },{
      "itemId": 3,
      "itemName": "Burger",
      'itemPrice': 200,
   },{
      "itemId": 4,
      "itemName": "Pizza",
      'itemPrice': 300,
   },
]
item = []
reciept = """
\t\tPRODUCT NAME -- COST
"""
sum = 0
run = True

print("------- Vending Machine Program with Python-------\n\n")
print("----------The Items In Stock Are----------\n\n")


for i in items_data:
   print(
      f"Item: {i['itemName']} --- Price: {i['itemPrice']} --- Item ID: {i['itemId']}")


def vendingMachine(items_data, run, item):
   while run:
      buyItem = int(
         input("\n\nEnter the item code for the item you want to buy: "))
      if buyItem < len(items_data):
         item.append(items_data[buyItem])
      else:
         print("THE PRODUCT ID IS WRONG!")
      moreItems = str(
         input("type any key to add more things, and type q to stop:  "))
      if moreItems == "q":
         run = False
   receiptValue = int(
      input(("1. Print the bill? 2. Only print the total sum: ")))
   if receiptValue == 1:
      print(createReceipt(item, reciept))
   elif receiptValue == 2:
      print(sumItem(item))
   else:
      print("INVALID")


def sumItem(item):
   sumItems = 0
   for i in item:
      sumItems += i["itemPrice"]
   return sumItems


def createReceipt(item, reciept):
   for i in item:
      reciept += f"""
      \t{i["itemName"]} -- {i['itemPrice']}
      """
   reciept += f"""
      \tTotal --- {sumItem(item)}
      """
   return reciept


# Main Code
vendingMachine(items_data, run, item)

Output

------- Vending Machine Program with Python-------


----------The Items In Stock Are----------


Item: Dairy Milk --- Price: 120 --- Item ID: 0
Item: 5Star --- Price: 30 --- Item ID: 1
Item: perk --- Price: 50 --- Item ID: 2
Item: Burger --- Price: 200 --- Item ID: 3
Item: Pizza --- Price: 300 --- Item ID: 4


Enter the item code for the item you want to buy: 2
type any key to add more things, and type q to stop:  t


Enter the item code for the item you want to buy: 3
type any key to add more things, and type q to stop:  q
1. Print the bill? 2. Only print the total sum: 1

		PRODUCT NAME -- COST

        	perk -- 50
        
        	Burger -- 200
        
        	Total --- 250

Conclusion

We studied how to create a vending machine program in Python and how the primary logic works in detail in this article.

Updated on: 31-Jan-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements