购物车作业详解
买家 卖家 商品 金钱
1 # 把货物放在货架上 2 li = [ 3 {'name':'苹果', 'price':1}, 4 {'name':'香蕉', 'price':1}, 5 {'name':'西瓜', 'price':10}, 6 {'name':'橘子', 'price':0.5}, 7 ] 8 shopping_car = {} # 建立一个空购物车 9 print('欢迎光临水果店') 10 money = input('让我看看你有多少钱:') 11 if money.isdigit() and int(money) > 0: 12 while 1: 13 for i,k in enumerate(li): 14 print('序号:{}\t商品:{}\t价格:{}'.format(i, k['name'], k['price'])) 15 choose = input('请输入您要购买的商品序号:') 16 if choose.isdigit() and int(choose) < len(li): 17 num = input('您要购买的商品数量:') 18 if num.isdigit(): 19 if int(money) > li[int(choose)]['price'] * int(num): 20 money = int(money) - li[int(choose)]['price'] * int(num) 21 if li[int(choose)]['name'] in shopping_car: 22 shopping_car[li[int(choose)]['name']] += int(num) # 若商品已经在购物车中, 则增加数量 23 else: 24 shopping_car[li[int(choose)]['name']] = int(num) 25 print('购物车中的商品有:{}\t\t您的余额为:{}'.format(shopping_car,money)) 26 else: 27 print('余额不足') 28 break 29 else: 30 print('您输入的序号有误')