Python Code Example: Vending Machine

A vending machine is a real-world object that dispenses items when money is inserted. It has functionalities such as displaying available products, accepting payments, dispensing items, and returning change.

In this example, we will create a VendingMachine class that includes:
Attributes: List of available products and their prices, machine balance.
Methods: Display products, accept payment, dispense items, and return change.
Encapsulation: Secure handling of balance and transactions.

This example demonstrates object-oriented programming (OOP) by encapsulating data (products, balance) and behavior (transactions, dispensing items) in a structured way.


Code Example

class VendingMachine:
    """Class representing a vending machine."""

    def __init__(self):
        """Initialize products and balance."""
        self.products = {
            "A1": {"name": "Soda", "price": 1.50},
            "A2": {"name": "Chips", "price": 2.00},
            "A3": {"name": "Candy", "price": 1.00}
        }
        self.balance = 0.0  # Machine balance

    def display_products(self):
        """Display available products and their prices."""
        print("Available Products:")
        for code, product in self.products.items():
            print(f"{code}: {product['name']} - ${product['price']:.2f}")

    def insert_money(self, amount):
        """Insert money into the vending machine."""
        if amount > 0:
            self.balance += amount
            print(f"Inserted ${amount:.2f}. Current balance: ${self.balance:.2f}")
        else:
            print("Please insert a valid amount.")

    def select_product(self, code):
        """Select a product and dispense it if enough money is inserted."""
        if code in self.products:
            product = self.products[code]
            if self.balance >= product["price"]:
                self.balance -= product["price"]
                print(f"Dispensing {product['name']}...")
                self.return_change()
            else:
                print(f"Insufficient balance! {product['name']} costs ${product['price']:.2f}.")
        else:
            print("Invalid product code.")

    def return_change(self):
        """Return any remaining change to the user."""
        if self.balance > 0:
            print(f"Returning change: ${self.balance:.2f}")
            self.balance = 0.0
        else:
            print("No change to return.")

# Creating a VendingMachine object
machine = VendingMachine()

# Using the vending machine
machine.display_products()
machine.insert_money(2.00)
machine.select_product("A2")  # Buying Chips

Output

Available Products:
A1: Soda - $1.50
A2: Chips - $2.00
A3: Candy - $1.00
Inserted $2.00. Current balance: $2.00
Dispensing Chips...
No change to return.

Code Explanation

  1. Defining the VendingMachine class
    • Stores available products and prices in a dictionary.
    • Maintains the current balance of the machine.
  2. Creating display_products() method
    • Displays the list of products along with their prices.
  3. Creating insert_money() method
    • Allows users to add money and updates the balance.
  4. Creating select_product() method
    • Checks if the product exists.
    • Dispenses the item if enough money is inserted.
  5. Creating return_change() method
    • Returns remaining balance to the user if applicable.
  6. Creating and using a vending machine object
    • Displays products.
    • User inserts $2.00 and buys Chips.
    • Since the price is $2.00, no change is returned.

Why Use OOP for this Example?

Encapsulation: Keeps balance management secure.
Code Reusability: Easily modify or add new products.
Scalability: Extend features like multiple payment options.

This example shows real-world OOP implementation, making the vending machine modular, reusable, and efficient! 🚀