product_list = [
['cup',8],
['iphone',7999],
['bag',149],
['notebook',3999],
['toy',80],
['noodles',13],
['pork',19],
['icecream',16]
] #定义商品列表
while True:
money = input("请输入你的拥有金额:")
if money.isdigit() and int(money) > 0: #判断输入是否数字及是否大于0的正整数
money = int(money)
break
else:
print("金额要为整数阿拉伯数字!")
for i in range(8):
print("序号:",i,",","商品:",product_list[i][0],",","单价:",product_list[i][1]) #打印商品列表
shopping_list = [] #购物列表
shopping_list_seq = [] #购买列表中商品对应序号的列表,该列表中每个元素的值与购买列表每个元素的第一个值一致
dict01 = {} #用于展示的字典,当选择了重复商品,可只显示一项及对应数量
total01 = 0 #总价
while True:
choice = input("请选择商品序号或‘end’结束:") #开始选择商品,输入商品序号
if choice.isdigit() and int(choice) in range(8): #判断序号是否数字及是否有效序号
shopping_list.append([int(choice),product_list[int(choice)][0],product_list[int(choice)][1]]) #已选商品相关信息添加到购物列表(商品可重复)
shopping_list_seq.append(int(choice)) #同时追加商品序号列表
elif choice == 'end':
for j in range(len(shopping_list)): #根据购物列表长度循环,将商品写入字典,用数量标记重复选择的商品
dict01[shopping_list[j][0]] = [shopping_list[j][1],shopping_list[j][2],shopping_list_seq.count(shopping_list_seq[j])] #购物列表里的序号为字典里的key,值分配为[商品名称,商品单价,商品数量]
print("您的选择商品请单如下:"
for k in dict01:
total01 = total01 + dict01[k][2] * dict01[k][1]
print("序号:",k,",","商品:",dict01[k][0],",","单价:",dict01[k][1],",","数量:",dict01[k][2],",","价格:",dict01[k][2]*dict01[k][1]) #打印已选清单
print("总计:",total01)
print("现有余额:", money)
print("消费后余额:",money - total01)
break
else:
print("请输入正确的商品序号或‘end’结束")
while True:
if total01 > money: #判断是否金额不足
dict01.clear()
print("您没有足够的金额,请减少选择的商品")
minus = input("请输入您要减少的商品序号或‘end’结束:")
if minus.isdigit() and int(minus) in shopping_list_seq: #判断删减的商品序号是否为数字及是否存在于序号列表
shopping_list.remove(shopping_list[shopping_list_seq.index(int(minus))]) #移除购物列表对应商品
shopping_list_seq.remove(int(minus)) #同时移除商品序号列表对应序号
for n in range(len(shopping_list)): #重新生成展示用的字典
dict01[shopping_list[n][0]] = [shopping_list[n][1], shopping_list[n][2],shopping_list_seq.count(shopping_list_seq[n])]
print("您的选择商品请单如下:")
total01 = 0
for o in dict01:
total01 = total01 + dict01[o][2] * dict01[o][1]
print("序号:", o, ",", "商品:", dict01[o][0], ",", "单价:", dict01[o][1], ",", "数量:", dict01[o][2], ",","价格:", dict01[o][2] * dict01[o][1])
print("总计:", total01)
elif minus == 'end':
break
else:
print("您输入的商品序号不在已选清单里")
else:
confirm = input("请输入y确认支付或输入n取消交易")
if confirm == 'y':
money = money - total01
print("您的购物请单如下2:")
for k in dict01:
print("序号:",k,",","商品:",dict01[k][0],",","单价:",dict01[k][1],",","数量:",dict01[k][2],",","价格:",dict01[k][2]*dict01[k][1])
print("总计:",total01)
print("余额:",money)
break
elif confirm == 'n':
print("交易已取消!")
break
else:
print("请按提示正确输入选项!")