作业要求:
智能库存管理系统 - 函数式实现
要求使用:函数、while循环、for循环、if条件判断、列表、字典、集合等容器
# 全局数据结构
products = {} # {商品ID: {"name": 名称, "price": 价格, "stock": 库存, "category": 类别, "sales": 销量}}
transactions = [] # [{"type": 类型, "product_id": 商品ID, "quantity": 数量, "timestamp": 时间}]
categories = set()
next_product_id = 1
def add_product(name, price, initial_stock, category):
**"""添加新商品"""**
**global next\_product\_id, products, categories**
**# 你的实现代码**
**pass**
def remove_product(product_id):
**"""删除商品"""**
**global products, transactions**
**# 你的实现代码**
**pass**
def update_product(product_id, **kwargs):
**"""更新商品信息"""**
**global products**
**# 你的实现代码**
**pass**
def stock_in(product_id, quantity):
**"""商品入库"""**
**global products, transactions**
**# 你的实现代码**
**pass**
def stock_out(product_id, quantity):
**"""商品出库"""**
**global products, transactions**
**# 你的实现代码**
**pass**
def find_slow_moving_products(threshold_days=30, min_sales=5):
**"""识别滞销商品"""**
**global products, transactions**
**# 你的实现代码**
**pass**
def calculate_inventory_turnover():
**"""计算库存周转率"""**
**global products, transactions**
**# 你的实现代码**
**pass**
def generate_replenishment_suggestion():
**"""生成补货建议"""**
**global products**
**# 你的实现代码**
**pass**
def display_inventory_report():
**"""显示库存报告"""**
**global products**
**# 你的实现代码**
**pass**
def main_menu():
**"""主菜单系统"""**
**while True:**
**print("\\n=== 智能库存管理系统 ===")**
**print("1. 添加商品")**
**print("2. 删除商品")**
**print("3. 更新商品信息")**
**print("4. 商品入库")**
**print("5. 商品出库")**
**print("6. 查看滞销商品")**
**print("7. 库存统计报告")**
**print("8. 补货建议")**
**print("9. 退出系统")**
**choice = input("请选择操作(1-9): ").strip()**
**if choice == '1':**
**# 调用添加商品函数**
**pass**
**elif choice == '9':**
**print("感谢使用库存管理系统!")**
**break**
**else:**
**print("功能开发中...")**
# 启动系统
if __name__ == "__main__":
**main\_menu()**
本文将详细解析一个完整的Python智能库存管理系统,通过这个项目你将学会如何综合运用函数、循环、条件判断和多种数据结构来构建实用的业务系统。
系统架构概述
首先让我们理解整个系统的架构设计:

第一部分:数据层设计
1.1 全局数据结构
python
import datetime
# 核心数据结构
products = {} # 商品主数据库
transactions = [] # 交易记录流水
categories = set() # 商品类别索引
next_product_id = 1 # ID**生成器

详细解析:
1.1.1 字典(Dictionary)- products
python
# 数据结构示例
products = {
1: {
"name": "苹果手机",
"price": 5999.0, *\#* *单价*
"stock": 50, *\#* *当前库存*
"category": "电子产品", *\#* *商品类别*
"sales": 0 *\#* *累计销量*
},
2: {
"name": "办公椅",
"price": 299.0,
"stock": 100,
"category": "办公用品",
"sales": 0
}
}

为什么选择字典?
- 快速查找:通过商品ID直接访问商品信息,时间复杂度O(1)
- 结构化存储:每个商品的信息以键值对形式组织,清晰明了
- 易于扩展:可以方便地添加新的商品属性字段
1.1.2 列表(List)- transactions
python
# 交易记录示例
transactions = [
{
"type": "入库", *\#* *交易类型*
"product\_id": 1, *\#* *关联商品ID*
"quantity": 10, *\#* *交易数量*
"timestamp": "2024-01-15 10:30:00" *\#* *交易时间*
},
{
"type": "出库",
"product\_id": 1,
"quantity": 5,
"timestamp": "2024-01-16 14:20:00"
}
]

为什么选择列表?
- 保持顺序:交易记录按时间顺序存储,便于追溯
- 动态增长:可以不断添加新的交易记录
- 遍历方便:使用for循环可以轻松处理所有记录
1.1.3 集合(Set)- categories
python
# 类别集合示例
categories = {"电子产品", "办公用品", "日用品"}

为什么选择集合?
- 自动去重:相同的类别只会存储一次
- 快速查找:检查某个类别是否存在很快
- 数学运算:支持交集、并集等操作(虽然本系统未用到)
第二部分:功能层实现
2.1 商品管理模块
2.1.1 添加商品函数
python
def add_product(name, price, initial_stock, category):
"""添加新商品"""
global next\_product\_id, products, categories
*\#* *输入验证 - if条件判断的典型应用*
if not name or price <= 0 or initial\_stock < 0:
print("错误:商品信息无效!")
return False
*\#* *创建商品字典*
products\[next\_product\_id\] = {
"name": name,
"price": price,
"stock": initial\_stock,
"category": category,
"sales": 0 *\#* *初始销量为0*
}
*\#* *使用集合存储类别*
categories.add(category)
print(f"成功添加商品:{name} (ID: {next\_product\_id})")
next\_product\_id += 1 *\# ID**自增*
return True

代码详解:
- 全局变量声明:global关键字用于修改全局变量
- 输入验证:使用if条件判断确保数据的有效性
- 字典操作:向products字典添加新的键值对
- 集合操作:使用add()方法向集合添加元素(自动去重)
- 用户反馈:提供清晰的操作结果反馈
2.1.2 删除商品函数
python
def remove_product(product_id):
"""删除商品"""
global products, transactions
*\#* *检查商品是否存在*
if product\_id not in products:
print(f"错误:商品ID {product\_id} 不存在!")
return False
*\#* *获取商品名称用于反馈*
product\_name = products\[product\_id\]\["name"\]
*\#* *使用del关键字删除字典元素*
del products\[product\_id\]
print(f"成功删除商品:{product\_name} (ID: {product\_id})")
return True

关键知识点:
- in运算符检查字典键是否存在
- del语句删除字典元素
- 错误处理的用户友好提示
2.1.3 更新商品函数
python
def update_product(product_id, **kwargs):
"""更新商品信息 - 使用\*\*kwargs接收可变参数"""
global products, categories
*\#* *存在性检查*
if product\_id not in products:
print(f"错误:商品ID {product\_id} 不存在!")
return False
product = products\[product\_id\]
valid\_fields = \["name", "price", "stock", "category"\]
*\#* *遍历所有传入的参数*
for field, value in kwargs.items():
*\#* *检查字段是否有效*
if field in valid\_fields:
*\#* *特殊处理类别更新*
if field == "category":
categories.add(value) *\#* *添加新类别到集合*
*\#* *更新商品字段*
product\[field\] = value
print(f"成功更新商品ID {product\_id} 的信息")
return True

高级特性:
- **kwargs:接收任意数量的关键字参数
- 字段验证:确保只更新有效的字段
- 集合的自动去重特性
2.2 库存操作模块
2.2.1 入库操作
python
def stock_in(product_id, quantity):
"""商品入库"""
global products, transactions
*\#* *多重条件验证*
if product\_id not in products:
print(f"错误:商品ID {product\_id} 不存在!")
return False
if quantity <= 0:
print("错误:入库数量必须大于0!")
return False
*\#* *更新库存 - 字典的嵌套访问*
products\[product\_id\]\["stock"\] += quantity
*\#* *创建交易记录*
transaction = {
"type": "入库",
"product\_id": product\_id,
"quantity": quantity,
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
*\#* *添加到交易列表*
transactions.append(transaction)
print(f"成功入库:{products\[product\_id\]\['name'\]} × {quantity}")
return True

业务逻辑分析:
- 前置验证:确保商品存在且数量有效
- 库存更新:直接修改字典中的库存值
- 记录追踪:创建完整的交易记录
- 时间处理:使用datetime模块记录精确时间
2.2.2 出库操作
python
def stock_out(product_id, quantity):
"""商品出库"""
global products, transactions
if product\_id not in products:
print(f"错误:商品ID {product\_id} 不存在!")
return False
*\#* *获取商品引用,避免重复字典查找*
product = products\[product\_id\]
if quantity <= 0:
print("错误:出库数量必须大于0!")
return False
*\#* *库存充足性检查*
if product\["stock"\] < quantity:
print(f"错误:库存不足!当前库存:{product\['stock'\]}")
return False
*\#* *更新库存和销量*
product\["stock"\] -= quantity
product\["sales"\] += quantity
*\#* *记录交易*
transaction = {
"type": "出库",
"product\_id": product\_id,
"quantity": quantity,
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
transactions.append(transaction)
print(f"成功出库:{product\['name'\]} × {quantity}")
return True

优化技巧:
- 引用缓存:product = products[product_id]避免多次字典查找
- 业务完整性:同时更新库存和销量,保证数据一致性
- 明确反馈:提供详细的成功/失败信息
2.3 智能分析模块
2.3.1 滞销商品分析
python
def find_slow_moving_products(threshold_days=30, min_sales=5):
"""识别滞销商品 - 展示复杂数据处理"""
global products, transactions
print(f"\\n=== 滞销商品分析 (最近{threshold\_days}天销量低于{min\_sales}) ===")
*\#* *计算时间阈值*
cutoff\_date = datetime.datetime.now() - datetime.timedelta(days=threshold\_days)
slow\_moving\_products = \[\] *\#* *结果列表*
*\#* *外层循环:遍历所有商品*
for product\_id, product in products.items():
recent\_sales = 0 *\#* *初始化近期销量*
*\#* *内层循环:遍历交易记录计算销量*
for transaction in transactions:
*\#* *多重条件筛选*
if (transaction\["type"\] == "出库" and
transaction\["product\_id"\] == product\_id):
*\#* *时间转换和比较*
transaction\_date = datetime.datetime.strptime(
transaction\["timestamp"\], "%Y-%m-%d %H:%M:%S")
*\#* *时间范围判断*
if transaction\_date >= cutoff\_date:
recent\_sales += transaction\["quantity"\]
*\#* *滞销判断条件*
if recent\_sales < min\_sales:
*\#* *构建结果字典*
slow\_moving\_products.append({
"id": product\_id,
"name": product\["name"\],
"recent\_sales": recent\_sales,
"stock": product\["stock"\]
})
*\#* *结果展示*
if slow\_moving\_products:
print("滞销商品列表:")
*\#* *遍历结果列表*
for product in slow\_moving\_products:
print(f"ID: {product\['id'\]}, 名称: {product\['name'\]}, "
f"最近销量: {product\['recent\_sales'\]}, 当前库存: {product\['stock'\]}")
else:
print("没有发现滞销商品")
return slow_moving_products

复杂逻辑解析:
- 嵌套循环:
- 外层:遍历所有商品
- 内层:遍历交易记录计算特定商品的销量
- 时间处理:
- datetime.timedelta计算时间间隔
- strptime将字符串转换为datetime对象
- 条件组合:
- 交易类型为"出库"
- 商品ID匹配
- 时间在指定范围内
- 数据聚合:
- 累加符合条件的交易数量
- 构建结构化的结果集
2.3.2 库存周转率计算
python
def calculate_inventory_turnover():
"""计算库存周转率 - 展示业务指标计算"""
global products, transactions
print("\\n=== 库存周转率分析 ===")
*\#* *初始化统计变量*
total\_cost\_of\_goods\_sold = 0 *\#* *销售成本总额*
total\_inventory\_value = 0 *\#* *库存价值总额*
*\#* *遍历所有商品进行计算*
for product\_id, product in products.items():
product\_sales = 0 *\#* *商品销量*
*\#* *计算商品总销量*
for transaction in transactions:
if (transaction\["type"\] == "出库" and
transaction\["product\_id"\] == product\_id):
product\_sales += transaction\["quantity"\]
*\#* *计算销售成本*
cost\_of\_goods\_sold = product\_sales \* product\["price"\]
total\_cost\_of\_goods\_sold += cost\_of\_goods\_sold
*\#* *计算库存价值*
inventory\_value = product\["stock"\] \* product\["price"\]
total\_inventory\_value += inventory\_value
*\#* *周转率计算和评估*
if total\_inventory\_value > 0:
inventory\_turnover = total\_cost\_of\_goods\_sold / total\_inventory\_value
print(f"库存周转率: {inventory\_turnover:.2f}")
*\#* *多条件评估*
if inventory\_turnover > 5:
print("周转率状态: 优秀")
elif inventory\_turnover > 2:
print("周转率状态: 良好")
else:
print("周转率状态: 需要改进")
else:
print("库存为空,无法计算周转率")
return total_cost_of_goods_sold, total_inventory_value

财务指标说明:
- 库存周转率 = 销售成本 / 平均库存价值
- 意义:衡量库存管理效率,越高说明库存流转越快
- 行业标准:不同行业标准不同,这里使用通用阈值
2.3.3 智能补货建议
python
def generate_replenishment_suggestion():
"""生成补货建议 - 简单的业务规则引擎"""
global products
print("\\n=== 补货建议 ===")
suggestions = \[\] *\#* *建议列表*
*\#* *遍历商品应用补货规则*
for product\_id, product in products.items():
*\#* *补货条件:库存低且有销售记录*
if product\["stock"\] < 10 and product\["sales"\] > 0:
*\#* *补货量计算:取最大值,避免建议量太小*
suggested\_quantity = max(20, product\["sales"\] // 2)
suggestions.append({
"id": product\_id,
"name": product\["name"\],
"current\_stock": product\["stock"\],
"suggested\_quantity": suggested\_quantity
})
*\#* *结果展示*
if suggestions:
print("需要补货的商品:")
for suggestion in suggestions:
print(f"ID: {suggestion\['id'\]}, 名称: {suggestion\['name'\]}, "
f"当前库存: {suggestion\['current\_stock'\]}, "
f"建议补货: {suggestion\['suggested\_quantity'\]}")
else:
print("所有商品库存充足,无需补货")
return suggestions

业务规则设计:
- 触发条件:
- 当前库存 < 10
- 历史销量 > 0(有需求的商品)
- 补货量算法:
- max(20, sales // 2):保证最小补货量,基于历史销量
2.4 统计报告模块
2.4.1 库存统计报告
python
def display_inventory_report():
"""显示库存报告 - 综合数据统计展示"""
global products
print("\\n=== 库存统计报告 ===")
*\#* *空库存检查*
if not products:
print("库存为空")
return
*\#* *按类别统计*
category\_stats = {} *\#* *类别统计字典*
*\#* *遍历商品进行分类统计*
for product in products.values():
category = product\["category"\]
*\#* *初始化类别统计*
if category not in category\_stats:
category\_stats\[category\] = {
"count": 0, *\#* *商品种类数*
"total\_value": 0, *\#* *总价值*
"total\_stock": 0 *\#* *总库存*
}
*\#* *累加统计值*
stats = category\_stats\[category\]
stats\["count"\] += 1
stats\["total\_stock"\] += product\["stock"\]
stats\["total\_value"\] += product\["stock"\] \* product\["price"\]
*\#* *总体统计计算*
total\_products = len(products)
total\_stock = sum(product\["stock"\] for product in products.values())
total\_value = sum(product\["stock"\] \* product\["price"\] for product in products.values())
*\#* *报告输出*
print(f"商品总数: {total\_products}")
print(f"总库存量: {total\_stock}")
print(f"总库存价值: {total\_value:.2f}元")
*\#* *类别明细*
print("\\n按类别统计:")
for category, stats in category\_stats.items():
print(f"{category}: {stats\['count'\]}种商品, "
f"库存{stats\['total\_stock'\]}, "
f"价值{stats\['total\_value'\]:.2f}元")
*\#* *商品明细*
print("\\n商品详情:")
for product\_id, product in products.items():
print(f"ID: {product\_id}, 名称: {product\['name'\]}, "
f"价格: {product\['price'\]}元, 库存: {product\['stock'\]}, "
f"类别: {product\['category'\]}, 销量: {product\['sales'\]}")

统计技巧:
- 字典分类统计:使用字典键作为分类依据
- 多重遍历:
- 第一次:分类和汇总
- 第二次:详细展示
- 生成器表达式:sum(product["stock"] for product in products.values())
2.4.2 交易历史查看
python
def display_transaction_history():
"""显示交易历史 - 列表切片应用"""
global transactions
print("\\n=== 交易历史 ===")
if not transactions:
print("暂无交易记录")
return
*\#* *显示最近20条记录,使用列表切片*
recent\_transactions = transactions\[-20:\]
*\#* *遍历显示,带序号*
for i, transaction in enumerate(recent\_transactions, 1):
*\#* *获取商品名称,处理商品可能被删除的情况*
product\_name = products.get(transaction\["product\_id"\], {}).get("name", "未知商品")
print(f"{i}. {transaction\['timestamp'\]} - {transaction\['type'\]} - "
f"{product\_name} × {transaction\['quantity'\]}")

实用特性:
- 列表切片:transactions[-20:]获取最后20个元素
- 安全访问:使用get()方法避免KeyError
- 枚举计数:enumerate(sequence, start=1)生成带序号的迭代
第三部分:表示层与控制层
3.1 主菜单系统
python
def main_menu():
"""主菜单系统 - while循环和条件判断的综合应用"""
*\#* *初始化示例数据*
init\_sample\_data()
*\#* *主循环 - 保持程序运行*
while True:
*\#* *菜单界面*
print("\\n" + "="\*40)
print(" 智能库存管理系统")
print("="\*40)
print("1. 添加商品")
print("2. 删除商品")
print("3. 更新商品信息")
print("4. 商品入库")
print("5. 商品出库")
print("6. 查看滞销商品")
print("7. 库存统计报告")
print("8. 补货建议")
print("9. 库存周转率")
print("10. 交易历史")
print("11. 退出系统")
*\#* *用户输入处理*
choice = input("\\n请选择操作(1-11): ").strip()
*\#* *多分支条件处理*
if choice == '1':
handle\_add\_product()
elif choice == '2':
handle\_remove\_product()
elif choice == '3':
handle\_update\_product()
elif choice == '4':
handle\_stock\_in()
elif choice == '5':
handle\_stock\_out()
elif choice == '6':
handle\_slow\_moving()
elif choice == '7':
display\_inventory\_report()
elif choice == '8':
generate\_replenishment\_suggestion()
elif choice == '9':
calculate\_inventory\_turnover()
elif choice == '10':
display\_transaction\_history()
elif choice == '11':
print("感谢使用库存管理系统!")
break *\#* *退出循环*
else:
print("无效选择,请重新输入!")

3.2 输入处理函数
3.2.1 添加商品处理
python
def handle_add_product():
"""处理添加商品输入"""
print("\\n--- 添加商品 ---")
name = input("商品名称: ").strip()
try:
price = float(input("商品价格: "))
stock = int(input("初始库存: "))
category = input("商品类别: ").strip()
add\_product(name, price, stock, category)
except ValueError:
print("错误:价格和库存必须是数字!")

3.2.2 库存操作处理
python
def handle_stock_in():
"""处理入库操作输入"""
print("\\n--- 商品入库 ---")
try:
product\_id = int(input("商品ID: "))
quantity = int(input("入库数量: "))
stock\_in(product\_id, quantity)
except ValueError:
print("错误:商品ID和数量必须是数字!")
第四部分:编程概念总结
4.1 函数设计原则
- 单一职责:每个函数只完成一个明确的任务
- 明确命名:函数名清晰表达其功能
- 参数验证:在函数开始处验证输入有效性
- 错误处理:提供有意义的错误信息
- 返回值设计:返回操作结果和必要数据
4.2 循环应用场景
- while循环:用于不确定次数的循环(主菜单)
- for循环:用于遍历已知的集合元素
- 嵌套循环:处理复杂的数据关系
4.3 条件判断技巧
- 简单if:单一条件检查
- if-else:二选一逻辑
- if-elif-else:多条件分支
- 嵌套条件:复杂业务规则
4.4 容器选择指南
|
容器类型
|
特点
|
适用场景
|
| --- | --- | --- |
|
字典
|
键值对,快速查找
|
商品数据、分类统计
|
|
列表
|
有序,可重复
|
交易记录、结果集合
|
|
集合
|
无序,唯一性
|
类别管理、去重操作
|
第五部分:扩展建议
5.1 功能扩展
- 数据持久化:添加文件保存/加载功能
- 用户认证:简单的登录系统
- 高级搜索:按名称、价格范围搜索商品
- 数据导出:生成Excel或PDF报告
5.2 代码优化
- 异常处理:更完善的错误处理机制
- 代码重构:将大型函数拆分为更小的函数
- 配置管理:将阈值参数提取为配置文件
- 单元测试:为每个函数编写测试用例
完整代码整合
python
"""
智能库存管理系统 - 函数式实现
要求使用:函数、while循环、for循环、if条件判断、列表、字典、集合等容器
"""
import datetime
# 全局数据结构
products = {} # {商品ID: {"name": 名称, "price": 价格, "stock": 库存, "category": 类别, "sales": 销量}}
transactions = [] # [{"type": 类型, "product_id": 商品ID, "quantity": 数量, "timestamp": 时间}]
categories = set()
next_product_id = 1
def add_product(name, price, initial_stock, category):
"""添加新商品"""
global next_product_id, products, categories
# 输入验证
if not name or price <= 0 or initial\_stock < 0:
print("错误:商品信息无效!")
return False
# 添加商品
products\[next\_product\_id\] = {
"name": name,
"price": price,
"stock": initial\_stock,
"category": category,
"sales": 0
}
# 更新类别集合
categories.add(category)
print(f"成功添加商品:{name} (ID: {next\_product\_id})")
next\_product\_id += 1
return True
def remove_product(product_id):
"""删除商品"""
global products, transactions
if product\_id not in products:
print(f"错误:商品ID {product\_id} 不存在!")
return False
product\_name = products\[product\_id\]\["name"\]
del products\[product\_id\]
print(f"成功删除商品:{product\_name} (ID: {product\_id})")
return True
def update_product(product_id, **kwargs):
"""更新商品信息"""
global products, categories
if product\_id not in products:
print(f"错误:商品ID {product\_id} 不存在!")
return False
product = products\[product\_id\]
valid\_fields = \["name", "price", "stock", "category"\]
for field, value in kwargs.items():
if field in valid\_fields:
if field == "category":
categories.add(value)
product\[field\] = value
print(f"成功更新商品ID {product\_id} 的信息")
return True
def stock_in(product_id, quantity):
"""商品入库"""
global products, transactions
if product\_id not in products:
print(f"错误:商品ID {product\_id} 不存在!")
return False
if quantity <= 0:
print("错误:入库数量必须大于0!")
return False
products\[product\_id\]\["stock"\] += quantity
# 记录交易
transaction = {
"type": "入库",
"product\_id": product\_id,
"quantity": quantity,
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
transactions.append(transaction)
print(f"成功入库:{products\[product\_id\]\['name'\]} × {quantity}")
return True
def stock_out(product_id, quantity):
"""商品出库"""
global products, transactions
if product\_id not in products:
print(f"错误:商品ID {product\_id} 不存在!")
return False
product = products\[product\_id\]
if quantity <= 0:
print("错误:出库数量必须大于0!")
return False
if product\["stock"\] < quantity:
print(f"错误:库存不足!当前库存:{product\['stock'\]}")
return False
product\["stock"\] -= quantity
product\["sales"\] += quantity
# 记录交易
transaction = {
"type": "出库",
"product\_id": product\_id,
"quantity": quantity,
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
transactions.append(transaction)
print(f"成功出库:{product\['name'\]} × {quantity}")
return True
def find_slow_moving_products(threshold_days=30, min_sales=5):
"""识别滞销商品"""
global products, transactions
print(f"\\n=== 滞销商品分析 (最近{threshold\_days}天销量低于{min\_sales}) ===")
# 计算最近threshold\_days天的销量
cutoff\_date = datetime.datetime.now() - datetime.timedelta(days=threshold\_days)
slow\_moving\_products = \[\]
for product\_id, product in products.items():
# 计算该商品在指定时间内的销量
recent\_sales = 0
for transaction in transactions:
if (transaction\["type"\] == "出库" and
transaction\["product\_id"\] == product\_id):
transaction\_date = datetime.datetime.strptime(
transaction\["timestamp"\], "%Y-%m-%d %H:%M:%S")
if transaction\_date >= cutoff\_date:
recent\_sales += transaction\["quantity"\]
if recent\_sales < min\_sales:
slow\_moving\_products.append({
"id": product\_id,
"name": product\["name"\],
"recent\_sales": recent\_sales,
"stock": product\["stock"\]
})
if slow\_moving\_products:
print("滞销商品列表:")
for product in slow\_moving\_products:
print(f"ID: {product\['id'\]}, 名称: {product\['name'\]}, "
f"最近销量: {product\['recent\_sales'\]}, 当前库存: {product\['stock'\]}")
else:
print("没有发现滞销商品")
return slow\_moving\_products
def calculate_inventory_turnover():
"""计算库存周转率"""
global products, transactions
print("\\n=== 库存周转率分析 ===")
# 计算总成本销售额和平均库存成本
total\_cost\_of\_goods\_sold = 0
total\_inventory\_value = 0
for product\_id, product in products.items():
# 计算该商品的销售成本
product\_sales = 0
for transaction in transactions:
if (transaction\["type"\] == "出库" and
transaction\["product\_id"\] == product\_id):
product\_sales += transaction\["quantity"\]
cost\_of\_goods\_sold = product\_sales \* product\["price"\]
total\_cost\_of\_goods\_sold += cost\_of\_goods\_sold
# 计算平均库存价值
inventory\_value = product\["stock"\] \* product\["price"\]
total\_inventory\_value += inventory\_value
# 计算库存周转率
if total\_inventory\_value > 0:
inventory\_turnover = total\_cost\_of\_goods\_sold / total\_inventory\_value
print(f"库存周转率: {inventory\_turnover:.2f}")
if inventory\_turnover > 5:
print("周转率状态: 优秀")
elif inventory\_turnover > 2:
print("周转率状态: 良好")
else:
print("周转率状态: 需要改进")
else:
print("库存为空,无法计算周转率")
return total\_cost\_of\_goods\_sold, total\_inventory\_value
def generate_replenishment_suggestion():
"""生成补货建议"""
global products
print("\\n=== 补货建议 ===")
suggestions = \[\]
for product\_id, product in products.items():
# 简单的补货逻辑:库存低于10且销量大于0的商品需要补货
if product\["stock"\] < 10 and product\["sales"\] > 0:
suggested\_quantity = max(20, product\["sales"\] // 2) # 建议补货量
suggestions.append({
"id": product\_id,
"name": product\["name"\],
"current\_stock": product\["stock"\],
"suggested\_quantity": suggested\_quantity
})
if suggestions:
print("需要补货的商品:")
for suggestion in suggestions:
print(f"ID: {suggestion\['id'\]}, 名称: {suggestion\['name'\]}, "
f"当前库存: {suggestion\['current\_stock'\]}, "
f"建议补货: {suggestion\['suggested\_quantity'\]}")
else:
print("所有商品库存充足,无需补货")
return suggestions
def display_inventory_report():
"""显示库存报告"""
global products
print("\\n=== 库存统计报告 ===")
if not products:
print("库存为空")
return
# 按类别统计
category\_stats = {}
for product in products.values():
category = product\["category"\]
if category not in category\_stats:
category\_stats\[category\] = {
"count": 0,
"total\_value": 0,
"total\_stock": 0
}
category\_stats\[category\]\["count"\] += 1
category\_stats\[category\]\["total\_stock"\] += product\["stock"\]
category\_stats\[category\]\["total\_value"\] += product\["stock"\] \* product\["price"\]
# 显示总体统计
total\_products = len(products)
total\_stock = sum(product\["stock"\] for product in products.values())
total\_value = sum(product\["stock"\] \* product\["price"\] for product in products.values())
print(f"商品总数: {total\_products}")
print(f"总库存量: {total\_stock}")
print(f"总库存价值: {total\_value:.2f}元")
# 显示按类别统计
print("\\n按类别统计:")
for category, stats in category\_stats.items():
print(f"{category}: {stats\['count'\]}种商品, "
f"库存{stats\['total\_stock'\]}, "
f"价值{stats\['total\_value'\]:.2f}元")
# 显示商品详情
print("\\n商品详情:")
for product\_id, product in products.items():
print(f"ID: {product\_id}, 名称: {product\['name'\]}, "
f"价格: {product\['price'\]}元, 库存: {product\['stock'\]}, "
f"类别: {product\['category'\]}, 销量: {product\['sales'\]}")
def display_transaction_history():
"""显示交易历史"""
global transactions
print("\\n=== 交易历史 ===")
if not transactions:
print("暂无交易记录")
return
for i, transaction in enumerate(transactions\[-20:\], 1): # 显示最近20条记录
product\_name = products.get(transaction\["product\_id"\], {}).get("name", "未知商品")
print(f"{i}. {transaction\['timestamp'\]} - {transaction\['type'\]} - "
f"{product\_name} × {transaction\['quantity'\]}")
def main_menu():
"""主菜单系统"""
while True:
print("\n" + "="*40)
print(" 智能库存管理系统")
print("="*40)
print("1. 添加商品")
print("2. 删除商品")
print("3. 更新商品信息")
print("4. 商品入库")
print("5. 商品出库")
print("6. 查看滞销商品")
print("7. 库存统计报告")
print("8. 补货建议")
print("9. 库存周转率")
print("10. 交易历史")
print("11. 退出系统")
choice = input("\\n请选择操作(1-11): ").strip()
if choice == '1':
print("\\n--- 添加商品 ---")
name = input("商品名称: ").strip()
try:
price = float(input("商品价格: "))
stock = int(input("初始库存: "))
category = input("商品类别: ").strip()
add\_product(name, price, stock, category)
except ValueError:
print("错误:价格和库存必须是数字!")
elif choice == '2':
print("\\n--- 删除商品 ---")
try:
product\_id = int(input("要删除的商品ID: "))
remove\_product(product\_id)
except ValueError:
print("错误:商品ID必须是数字!")
elif choice == '3':
print("\\n--- 更新商品信息 ---")
try:
product\_id = int(input("要更新的商品ID: "))
if product\_id in products:
print("可更新字段:name, price, stock, category")
field = input("要更新的字段: ").strip()
value = input("新值: ").strip()
# 类型转换
if field in \["price", "stock"\]:
try:
value = float(value) if field == "price" else int(value)
except ValueError:
print("错误:价格必须是数字,库存必须是整数!")
continue
update\_product(product\_id, \*\*{field: value})
else:
print("商品ID不存在!")
except ValueError:
print("错误:商品ID必须是数字!")
elif choice == '4':
print("\\n--- 商品入库 ---")
try:
product\_id = int(input("商品ID: "))
quantity = int(input("入库数量: "))
stock\_in(product\_id, quantity)
except ValueError:
print("错误:商品ID和数量必须是数字!")
elif choice == '5':
print("\\n--- 商品出库 ---")
try:
product\_id = int(input("商品ID: "))
quantity = int(input("出库数量: "))
stock\_out(product\_id, quantity)
except ValueError:
print("错误:商品ID和数量必须是数字!")
elif choice == '6':
try:
threshold = input("滞销判定天数(默认30): ").strip()
min\_sales = input("最低销量阈值(默认5): ").strip()
threshold = int(threshold) if threshold else 30
min\_sales = int(min\_sales) if min\_sales else 5
find\_slow\_moving\_products(threshold, min\_sales)
except ValueError:
print("错误:请输入有效的数字!")
elif choice == '7':
display\_inventory\_report()
elif choice == '8':
generate\_replenishment\_suggestion()
elif choice == '9':
calculate\_inventory\_turnover()
elif choice == '10':
display\_transaction\_history()
elif choice == '11':
print("感谢使用库存管理系统!")
break
else:
print("无效选择,请重新输入!")
# 启动系统
if __name__ == "__main__":
# 添加一些示例数据用于测试
print("正在初始化示例数据...")
add\_product("苹果手机", 5999.0, 50, "电子产品")
add\_product("笔记本电脑", 7999.0, 30, "电子产品")
add\_product("办公椅", 299.0, 100, "办公用品")
add\_product("咖啡杯", 25.0, 200, "日用品")
add\_product("无线鼠标", 89.0, 80, "电子产品")
# 添加一些示例交易记录
stock\_out(1, 5) # 售出5部苹果手机
stock\_out(2, 3) # 售出3台笔记本电脑
stock\_in(1, 10) # 苹果手机入库10部
stock\_out(3, 15) # 售出15把办公椅
print("系统初始化完成!")
main\_menu()
这个详细的分布解析涵盖了从基础数据结构到复杂业务逻辑的所有方面,通过这个项目你不仅学会了Python编程,还掌握了如何设计和实现一个完整的业务系统。每个函数都体现了良好的编程实践,是学习Python项目开发的优秀范例。