1 ''' 2 goods = [{"name":"电脑","price":1999}, 3 {"name":"鼠标","price":10}, 4 {"name":"键盘","price":20}, 5 {"name":"耳机","price":199} 6 ] 7 8 money=input() 9 shopping_car = [name=电脑,count:3]#append 不想买按Q退出 10 11 1,展示商品 12 1、电脑 1999 13 2、鼠标 10 14 3、键盘 20 15 4、耳机 199 16 1、输入的是全部数字,范围1-n(动态)len 17 扩展: 18 想买几个 19 购物车列表展示 20 购买成功,打印购买的商品列表 21 ''' 22 23 goods = [{"name":"电脑","price":1999}, 24 {"name":"鼠标","price":10}, 25 {"name":"键盘","price":20}, 26 {"name":"耳机","price":199} 27 ] 28 shopping_car=[]#购物车 29 purse=0#钱包余额 30 print('欢迎选购商品') 31 print('商品展示') 32 goods_id=1#商品列表中商品序号 33 for i in goods: 34 print(goods_id,'、',i["name"],' 价格:',i["price"],'元') 35 goods_id+=1 36 flag = True#标志位 37 while flag: 38 id=input('请输入您要购买的商品的序号:').strip() 39 while not(id.isdigit()and int(id)>0 and int(id)<=len(goods)): 40 print('注意:输入商品的序号必须是整数,并且在1到',len(goods),'范围之间') 41 id=input('请重新输入您要购买的商品的序号:') 42 else: 43 id=int(id)-1#输入id与商品列表中的索引位置相差一个 44 count=input('请输入您要购买的商品的个数:').strip() 45 while not(count.isdigit() and int(count)>0): 46 print('注意:输入商品的数量必须是大于0的整数') 47 count=input('请重新输入您要购买的商品的序号:') 48 else: 49 count=int(count) 50 shopping_car.append({'name':goods[id]["name"],'数量':count,'总价':goods[id]["price"]*count}) 51 print('您的购物车商品如下:') 52 shopping_car_id=1#购物车列表中商品序号 53 for i in shopping_car: 54 print(shopping_car_id,'、',i["name"], ' 数量',i['数量'],'个' ,' 总价:',i['总价'],'元') 55 shopping_car_id+=1 56 choise=input('继续添加商品请输入Y,结算请输入S,否则退出选购商品?') 57 if choise == 'Y':#继续选购商品 58 flag = True 59 elif choise == 'S':#结算购物车商品 60 total_money = 0#购物车商品总价 61 for i in shopping_car: 62 money = i['总价'] 63 total_money += money 64 print('您的购物总金额为:', total_money, '元') 65 print('您的钱包的余额为:', purse, '元') 66 while purse<total_money: 67 sum = input('您钱包余额不足,请充值:')#充值金额 68 while not (sum.isdigit()): 69 print('注意:输入的充值金额必须是整数') 70 sum = input('请重新输入您的充值金额:') 71 else: 72 purse =purse + int(sum) 73 print('您钱包的余额为:',purse, '元') 74 choise = input('进行支付请输入Y,继续进行选购商品请输入S,否则退出选购商品?') 75 if choise=='Y': 76 if (purse >= total_money):# 77 purse=purse-total_money 78 print('支付成功,您钱包的余额为',purse,'元') 79 m=1 80 print('订单详情'.center(30,'*')) 81 for i in shopping_car: 82 print(m, '、', i["name"], ' 数量', count, '个', ' 总价:', i['总价'], '元') 83 m+=1 84 print('订单总额:',total_money,'元') 85 print('*'*34) 86 shopping_car.clear() 87 choise = input('重新选购商品请输入Y,否则退出选购商品?') 88 if choise == 'Y': 89 flag = True 90 else: 91 print('再见,记得常来逛逛哦!') 92 flag = False 93 elif choise=='S': 94 flag = True 95 else: 96 print('再见,记得常来逛逛哦!') 97 flag = False 98 else: 99 print('再见,记得常来逛逛哦!') 100 flag = False