关键词搜索

源码搜索 ×
×

python通过字典实现购物车案例-用户端

发布2021-09-02浏览456次

详情内容

  1. import os
  2. dict01 = {
  3. 'iphone' : {
  4. '5999' : {
  5. '总部位于美国' : '价格相对较贵',
  6. },
  7. },
  8. 'wahaha' : {
  9. '15' : {
  10. '总部位于中国' : '经济实惠,大众喜爱',
  11. },
  12. },
  13. 'MacBook Air' : {
  14. '15000' : {
  15. '苹果公司笔记本' : '性能优越,续航惊人',
  16. },
  17. },
  18. '矿泉水' : {
  19. '2' : {
  20. '产自山区,富含矿物质' : '解渴,人人需要',
  21. },
  22. },
  23. }
  24. if os.path.exists('money.txt') :
  25. with open('money.txt', "r", encoding='utf-8-sig') as m01:
  26. budget = m01.read()
  27. budget = budget.strip()
  28. answer = input("当前预算为{0},是否增加预算?(y/n)".format(budget))
  29. if answer == 'y' :
  30. budgetNew = input("你的预算是多少?")
  31. budget = int(budgetNew) + int(budget)
  32. print("目前预算为{0}".format(budget))
  33. else :
  34. budget = input("你的预算是多少?")
  35. Continue = False
  36. shoppingCart = []
  37. budget = int(budget)
  38. while not Continue :
  39. # budget 购买物资预算
  40. print("商品清单如下:")
  41. # 将商品名称取出,保存到列表中
  42. product = list(dict01.keys())
  43. # 遍历输出所有的商品
  44. for index,list01 in enumerate(product):
  45. print(index,list01,list(dict01[list01].keys())[0] + "元")
  46. choice = input("请输入你的选择是:")
  47. # 判断输出值是否为数字
  48. if choice.isdigit():
  49. # 字符串转换为数字类型
  50. choice = int(choice)
  51. if choice < len(product) and choice >= 0:
  52. # 获取商品价格
  53. shoppingName = product[choice]
  54. # print(shoppingName)
  55. choicePrice = int(list(dict01[shoppingName].keys())[0])
  56. if budget >= choicePrice :
  57. # 选购商品保存在列表中
  58. shoppingCart.append(product[choice])
  59. budget -= choicePrice
  60. print("你的余额还有" + str(budget) + "元。")
  61. else :
  62. print("你买不起这个商品!")
  63. else :
  64. print("没有这个商品,请重新选择。")
  65. break
  66. elif choice == 'q':
  67. Continue = True
  68. print("\n你购买的清单如下:")
  69. print(shoppingCart)
  70. print("你的余额还有" + str(budget) + "元。\n")
  71. with open('money.txt', "w", encoding='utf-8-sig') as m :
  72. m.write(str(budget))
  73. break
  74. else :
  75. print("请重新输入,按q退出!")
  76. break

python教程

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载