Python 商品库存管理系统:字典实现示例

本文将介绍使用 Python 字典实现一个简单的商品库存管理系统。这个系统可以帮助商店管理商品信息,包括添加新商品、更新现有商品、删除商品和查询商品信息。

系统实现

一个简单的实现方式是使用一个包含所有商品信息的字典,其中每个键都是商品的唯一编号,每个值都是一个包含名称、描述和价格的列表。

以下是一个示例代码:

inventory = {
    '001': ['T-Shirt', 'A basic cotton T-shirt', 10.99],
    '002': ['Jeans', 'A pair of blue jeans', 29.99],
    '003': ['Sneakers', 'A pair of white sneakers', 39.99]
}

# 添加新商品
def add_new_product(product_id, product_name, product_description, product_price):
    inventory[product_id] = [product_name, product_description, product_price]

# 更新现有商品
def update_product(product_id, product_name=None, product_description=None, product_price=None):
    if product_id in inventory:
        if product_name:
            inventory[product_id][0] = product_name
        if product_description:
            inventory[product_id][1] = product_description
        if product_price:
            inventory[product_id][2] = product_price
    else:
        print('Product not found')

# 删除商品
def delete_product(product_id):
    if product_id in inventory:
        del inventory[product_id]
    else:
        print('Product not found')

# 查询商品信息
def get_product_info(product_id):
    if product_id in inventory:
        return inventory[product_id]
    else:
        print('Product not found')

使用示例

使用这些函数,商店可以轻松地管理他们的商品库存。例如,添加一个新商品:

add_new_product('004', 'Hoodie', 'A warm hoodie for cold weather', 24.99)

更新现有商品的价格:

update_product('003', product_price=49.99)

删除一个商品:

delete_product('002')

查询一个商品的信息:

get_product_info('001')
# Output: ['T-Shirt', 'A basic cotton T-shirt', 10.99]

总结

本示例展示了使用 Python 字典实现简单的商品库存管理系统。这种方法简单易懂,适合初学者学习 Python 编程和数据结构应用。对于更复杂的库存管理需求,可以考虑使用数据库等更强大的工具。

Python 商品库存管理系统:字典实现示例

原文地址: https://www.cveoy.top/t/topic/oSYO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录