一个简单的购物车例子练习
1 #coding:utf-8 2 3 ''' 4 购物车: 5 显示商品和购买价格。 6 购入商品,加入购物车。 7 付款,余额不足时提示,并可重新购买。 8 ''' 9 10 shop_cart = [] 11 amount = 0 12 wallet = 100 13 commodity = {"大米":60,"香蕉":8,"饼干":12,"榴莲":17} 14 15 print("商品名称:\t金额(元):") 16 for k,v in commodity.items(): 17 print("%s\t\t%s"%(k,v)) 18 19 while True: 20 print("\n结账请输入[B],重新购买请输入[R],退出请输入[Q]") 21 shop = input("请输入购买商品名称:") 22 if isinstance(shop,str): 23 if shop == "Q": 24 print("\nGoodbye Baby!!") 25 break 26 if shop == "R": 27 print("\nI am back. baby!!") 28 continue 29 elif shop == "B": 30 for i in shop_cart: 31 amount += commodity[i] 32 if wallet < amount: 33 print("\n余额不足!!\n供需付款 %s (元),\n剩余金额 %s (元)"%(amount,wallet)) 34 else: 35 wallet -= amount 36 for i in shop_cart: 37 print("%s %s (元)" % (i, commodity[i])) 38 print("=================\n账单:%s (元)"%amount) 39 print("余额 %s (元)"%wallet) 40 elif shop in commodity.keys(): 41 shop_cart.append(shop) 42 print("\n购物车:") 43 for n in shop_cart: 44 print("----------\n%s\t%s (元)"%(n,commodity[n])) 45 else: 46 print("\n输入有误,请输入需要购买商品的名称!!!\n") 47 else: 48 print("\n输入有误,请输入需要购买商品的名称!!!\n")