How do you code a vending machine in Python?

In this article, we will learn to code a vending machine in Python. A vending machine program simulates the functionality of a real vending machine where users can select items, view their cart, and get a bill.

Project Structure

Our vending machine will have the following components ?

  • Items Data: A list of dictionaries containing product information
  • Shopping Cart: A list to store selected items
  • Menu Display: Function to show available items
  • Purchase Logic: Handle item selection and validation
  • Bill Generation: Calculate total and display receipt

Setting Up Items Data

First, we define our inventory with item details ?

# Items available in the vending machine
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,
    },
]

# Shopping cart to store selected items
cart = []

# Receipt template
receipt_template = """
\t\tPRODUCT NAME -- COST
"""

Displaying the Menu

We create a function to display all available items with their details ?

def display_menu(items):
    print("------- Vending Machine Program -------\n")
    print("----------Available Items----------\n")
    
    for item in items:
        print(f"Item: {item['itemName']} --- Price: ?{item['itemPrice']} --- ID: {item['itemId']}")

# Display the menu
display_menu(items_data)
------- Vending Machine Program -------

----------Available Items----------

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

Calculating Total Price

This function calculates the total cost of items in the cart ?

def calculate_total(cart):
    total = 0
    for item in cart:
        total += item["itemPrice"]
    return total

# Example usage
sample_cart = [
    {"itemName": "Dairy Milk", "itemPrice": 120},
    {"itemName": "5Star", "itemPrice": 30}
]

print(f"Total cost: ?{calculate_total(sample_cart)}")
Total cost: ?150

Creating Receipt

This function generates a detailed receipt showing all purchased items ?

def create_receipt(cart, template):
    receipt = template
    
    for item in cart:
        receipt += f"""
        \t{item["itemName"]} -- ?{item['itemPrice']}
        """
    
    receipt += f"""
        \t--------------------------------
        \tTotal Amount: ?{calculate_total(cart)}
        """
    return receipt

# Example receipt
sample_receipt = create_receipt(sample_cart, receipt_template)
print(sample_receipt)

		PRODUCT NAME -- COST

        	Dairy Milk -- ?120
        
        	5Star -- ?30
        
        	--------------------------------
        	Total Amount: ?150
        

Main Vending Machine Logic

The core function that handles user interaction and purchase process ?

def vending_machine(items_data, cart):
    shopping = True
    
    while shopping:
        try:
            # Get item selection from user
            item_id = int(input("\nEnter item ID to purchase: "))
            
            # Validate item ID
            if 0 <= item_id < len(items_data):
                cart.append(items_data[item_id])
                print(f"Added {items_data[item_id]['itemName']} to cart!")
            else:
                print("Invalid item ID! Please try again.")
                continue
                
        except ValueError:
            print("Please enter a valid number!")
            continue
        
        # Ask if user wants more items
        more_items = input("Press 'q' to checkout or any key to continue: ").lower()
        if more_items == 'q':
            shopping = False
    
    # Checkout process
    if cart:
        print(f"\nItems in cart: {len(cart)}")
        choice = input("1. View detailed receipt  2. View total only: ")
        
        if choice == '1':
            print(create_receipt(cart, receipt_template))
        elif choice == '2':
            print(f"Total Amount: ?{calculate_total(cart)}")
        else:
            print("Invalid choice!")
    else:
        print("No items purchased!")

# Example usage (commented out for demo)
# vending_machine(items_data, cart)

Complete Vending Machine Program

Here's the complete working vending machine program ?

# Complete Vending Machine Program
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},
]

def display_menu(items):
    print("------- Vending Machine Program -------\n")
    for item in items:
        print(f"ID: {item['itemId']} | {item['itemName']} - ?{item['itemPrice']}")

def calculate_total(cart):
    return sum(item["itemPrice"] for item in cart)

def create_receipt(cart):
    receipt = "\n\t\t--- RECEIPT ---\n"
    for item in cart:
        receipt += f"\t{item['itemName']} - ?{item['itemPrice']}\n"
    receipt += f"\t{'='*25}\n"
    receipt += f"\tTotal: ?{calculate_total(cart)}\n"
    return receipt

# Demo simulation (without user input for online execution)
cart = []
display_menu(items_data)

# Simulate adding items to cart
cart.append(items_data[1])  # 5Star
cart.append(items_data[3])  # Burger

print(f"\nSimulated purchase: {[item['itemName'] for item in cart]}")
print(create_receipt(cart))
------- Vending Machine Program -------

ID: 0 | Dairy Milk - ?120
ID: 1 | 5Star - ?30
ID: 2 | Perk - ?50
ID: 3 | Burger - ?200
ID: 4 | Pizza - ?300

Simulated purchase: ['5Star', 'Burger']

		--- RECEIPT ---
	5Star - ?30
	Burger - ?200
	=========================
	Total: ?230

Key Features

Feature Function Purpose
Menu Display display_menu() Show available items
Add to Cart Item validation Prevent invalid selections
Calculate Total calculate_total() Sum up cart items
Generate Receipt create_receipt() Detailed purchase summary

Conclusion

This vending machine program demonstrates key programming concepts like data structures, user input validation, and modular function design. The program can be easily extended to include features like inventory management, payment processing, or change calculation.

Updated on: 2026-03-27T00:10:25+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements