#定义仓库
repos = dict()
#定义购物清单对象
shop_list = []
#定义函数来初始化商品
def init_repository():
goods1 = ("1001","鼠标",45)
goods2 = ("1002","键盘",78)
goods3 = ("1003","毛笔字帖",21.5)
goods4 = ("1004","算法竞赛",89)
goods5 = ("1005","声律启蒙",35)
goods6 = ("1006","Python爬虫",118)
#把商品放入dict中(入库),条码作为key
repos[goods1[0]] = goods1
repos[goods2[0]] = goods2
repos[goods3[0]] = goods3
repos[goods4[0]] = goods4
repos[goods5[0]] = goods5
repos[goods6[0]] = goods6
#定义函数,显示超市商品清单,即遍历字典dict
def show_goods():
print('欢迎光临 独狼超市')
print('超市的商品清单为:')
print("%13s%30s%12s" % ("条码","商品名称","单 价"))
#遍历repos中所有value来显示商品清单
for goods in repos.values():
print("%15s%30s%12s" % goods)
#定义函数,显示购物清单(遍历shop_list列表)
def show_list():
print("="*100)
#如果清单不为空,则输出清单的内容
if not shop_list:
print("还未购买商品")
else:
title = "%-5s | %15s | %30s | %10s | %4s | %10s" % ("ID","条码","商品名称","单价","数量","小计")
print(title)
print("-"*100)
#记录总计的价钱
sum = 0
#遍历购物清单shop_list
for i,item in enumerate(shop_list):
id = i + 1 #转换id为索引加1
code = item[0] #获取商品条码
name = repos[code][1] #获取商品名称
price = repos[code][2] #获取商品单价
number = item[1] #获取商品数量
amount = price * number #小计
sum = sum + amount #总计
line = "%-5s | %17s | %30s | %12s | %6s | %12s "% (id,code,name,price,number,amount)
print(line)
print("-"*100)
print(" 总计:",sum)
print("="*100)
#定义函数,添加购买的商品(向shop_list中添加项)
def add():
code = input("请输入商品的条码:
")
#若没有找到对应的商品,则输出条目错误
if code not in repos:
print("条码错误,请重新输入!")
return
goods = repos[code] #根据条码找商品
number = input("请输入购买的数量:
")
shop_list.append([code,int(number)]) #把商品和购买数量封装成list后加入到购物清单中
#定义函数,修改购买商品的数量
def edit():
id = input("请输入要修改的购物单的ID:
")
index = int(id)-1 #id减1得到购物单的索引
item = shop_list[index] #根据索引获取购物清单
number = input("请输入新的购买数量:
")
item[1] = number #修改item里面的number
#定义函数,删除购物清单项
def delete():
id = input("请输入要删除的购物清单的ID:
")
index = int(id) - 1
del shop_list[index]
#退出系统函数
def payment():
show_list() #先打印清单
print('
'*3)
print("欢迎下次光临")
import os
os._exit(0)
cmd_dict = {'a':add,'e':edit,'d':delete,'p':payment,'s':show_goods}
#定义函数,显示命令提示
def show_command():
cmd = input("请输入操作指令:
"+" 添加(a) 修改(e) 删除(d) 结算(p) 超市商品(s)
")
if cmd not in cmd_dict:
print("输入有误,请重新输入")
else:
cmd_dict[cmd]()
init_repository()
show_goods()
while True:
show_list()
show_command()