li = [{‘name‘: ‘手机‘, ‘price‘: ‘4999‘},
{‘name‘: ‘电脑‘, ‘price‘: ‘10999‘},
{‘name‘: ‘耳机‘, ‘price‘: ‘499‘},
{‘name‘: ‘鼠标‘, ‘price‘: ‘299‘},
{‘name‘: ‘键盘‘, ‘price‘: ‘599‘},
]
shopping_car = {} # 定义购物车dict
print(‘欢迎光临尚雅梦想旗舰店‘.center(40))
# 先让顾客输入携带的金钱数量,再显示商品列表(方便后续升级版可以根据金额多少推荐不同价位的商品,千人千面)
money = input(‘请输入您所携带的金钱数量:‘).strip() # 这里将顾客输入的字符串前后空格去掉,使用strip
f_money = int(money)
for i, k in enumerate(li, 1): # 使用enumerate参数遍历可迭代对象list列表,同时获取索引和值
print(‘序号{}\t\t名称:{}\t\t价格:{}元/个‘.format(i, k[‘name‘], k[‘price‘])) # 使用format占位
flag = True
while flag:
choose = input(‘‘‘请输入您要购买的商品序号:退出请按‘q‘或者‘Q‘‘‘‘‘).strip()
if choose.upper() == ‘Q‘:
break
if choose.isdigit() and int(choose) <= len(li): # 判断输入的序号是否符合
num = input(‘请输入您要购买的数量‘).strip()
if num.isdigit():
if int(money) > int(li[int(choose) - 1][‘price‘]) * int(num):
money = int(money) - int(li[int(choose) - 1][‘price‘]) * int(num)
else:
print(‘抱歉!您所携带的金额不足,请补充后再进行购物。‘)
break
if li[int(choose) - 1][‘name‘] in shopping_car:
print(‘‘‘您的购物车里已经有{}个{}‘‘‘.format(int(shopping_car[li[int(choose) - 1][‘name‘]]),
li[int(choose) - 1][‘name‘]))
order = input(‘‘‘继续添加请按‘y‘或者‘Y‘,按其他重新选择‘‘‘).strip()
if order.upper() == ‘Y‘:
shopping_car[li[int(choose) - 1][‘name‘]] = shopping_car[li[int(choose) - 1][‘name‘]] + int(num)
else:
continue
else:
shopping_car[li[int(choose) - 1][‘name‘]] = int(num)
else:
print(‘您的输入有误,请重新输入:‘)
print(‘您的购物车里有{},本次消费一共花费{}元,余额为{}元‘.format(shopping_car, f_money - money, money))
升级版购物车代码,后续将继续根据学习的内容逐步完善更新
原文:https://www.cnblogs.com/xuminzgl/p/11882788.html