python每日一题:利用字典实现超市购物程序

购物车程序:
需求:

1. 启动程序,让用户输入工资,然后打印商品列表;

2.允许用户根据商品编号或者商品名字购买商品;

3.用户输入商品列表后检测余额是否足够,够就直接扣款,不够就提醒;

4.用户可以一直购买商品,也可以直接退出,退出后打印已购买商品和余额;

    • balance=0
      shoplist=[{'identifier':1,'apple':5},{'identifier':2,'banana':4},{'identifier':3,'cake':20},{'identifier':4,'shoe':99},{'identifier':5,'diamond':200}]
      shoplist1,shoplist2,shoplist3=[],[],[]
      shop_cart={}
      for i in shoplist:
          k=i
          del k['identifier']
          shoplist1.append(k)#提取出商品名称和单价
          shoplist2.append(list(k.keys())[0])#单独提取出商品名称
          shoplist3.append(list(k.values())[0])#单独提取出商品单价
      salary=int(input('please input your salary:'))
      print("the selective menu are as follwed:")
      print(shoplist)
      print('please select your want goods:')
      while 1:
          want=input()    #可以输入商品的数字编号或者商品名字
          if  want.isdigit() and int(want) in range(1,len(shoplist)+1):
              want=int(want)
              goods=shoplist2[want - 1]
              price=shoplist3[want - 1]
          elif  want in shoplist2:
              p = shoplist2.index(want)
              goods=want
              price=shoplist3[p]
          else:
              print("the goods is not existed, please input again")
              continue
          print('you has selected:',goods, ',its price:', price)
          quantity = int(input('please input the quantity of the goods:'))
          if salary>=quantity*price:
              salary-=quantity*price
              balance+=quantity*price
              shop_cart[goods]={price:quantity}
          else:
              print('sorry,you can not afford it')
          print("you can input any word to keep shopping or input 'N'to end shopping")
          s=input()
          if s!='N':
              continue
          else:
              break
      print('your shoppinglist is as follows:')
      print(shop_cart)
      print('your shopping consuption is:',balance)

      编译结果如下:

      your shoppinglist is as follows:
      {'diamond': {200: 10}, 'apple': {5: 10}}
      your shopping consuption is: 2050
原文地址:https://www.cnblogs.com/xuehaiwuya0000/p/10141154.html