Inventory Management

Create a class Inventory that can store different products and their quantities. The class should have methods for adding a product, removing a product, updating the quantity of a product, and finding the total value of the inventory.

Example 1:

inventory = Inventory()
inventory.add_product("Apples", 2, 10)
inventory.add_product("Bananas", 1.5, 15)
inventory.update_quantity("Apples", 20)


Use a dictionary to store the products and their corresponding prices and quantities. The dictionary keys can be the product names and the dictionary values can be another dictionary with “price” and “quantity” as keys.

class Inventory:
    def __init__(self):
        self.products = {}

    def add_product(self, name, price, quantity):
        self.products[name] = {"price": price, "quantity": quantity}

    def remove_product(self, name):
        if name in self.products:
            del self.products[name]

    def update_quantity(self, name, quantity):
        if name in self.products:
            self.products[name]["quantity"] = quantity

    def find_total_value(self):
        total = 0
        for product in self.products.values():
            total += product["price"] * product["quantity"]
        return total

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!