Day3 Python-购物车程序

功能要求:
基础要求: 1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表 2、允许用户根据商品编号购买商品 3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 4、可随时退出,退出时,打印已购买商品和余额 5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示 扩展需求: 1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买 2、允许查询之前的消费记录

数据结构:
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]

                  


 思路:

1、用户登录可以参考 Day1 Python-编写登陆认证程序,可以实现多用户登录,升级需求可一样的设计。

2、数据结构为列表嵌套字典,并且要求通过商品编号购买商品,可以用enumerate()枚举函数,将列表索引用作商品编号。

3、在输入商品编号的时候需要注意,input()接收到的都是字符串,要进行一个判断输入的是否是数字(chioce.isdigit()

),若是数字将输入的参数改为int类型。

4、输入过后判断chioce是否在商品列表取值范围内,如果在就判断余额是否够,够的话就加入购物车并且扣款,并打印余额;如果余额不足,打印余额不足。如果chioce不在商品列表中则打印无此商品。

5、文件存储格式

{'shopping_cart': {},    # 购物车记录
'salary': 0,    # 工资余额
'account': ['abc123'],    # 用户密码
}

6、构造购物车数据格式,字典嵌套字典

{‘name’: {'count':0,'sub_total':0}
}

代码:

 1 #!/usr/bin/env python
 2 # -*- coding=utf-8 -*-
 3 """
 4 @author:Wllen
 5 @file:shopping_cart.py
 6 @time:2018/5/30 13:42
 7 """
 8 goods = [
 9 {"name": "电脑", "price": 1999},
10 {"name": "鼠标", "price": 10},
11 {"name": "游艇", "price": 20},
12 {"name": "美女", "price": 998},
13 ]
14 import os
15 run_flag = True
16 while run_flag:
17     username = input('请输入您的用户名:').strip()
18     userpasswd = input('请输入您的密码:').strip()
19     account_file = "db/%s.db" % username
20     if os.path.isfile(account_file):
21         f = open(account_file, 'r', encoding='utf-8')
22         data = eval(f.read())
23         f.close()
24         if userpasswd == data.get('account')[0]:  # get去字典值
25             print("欢迎%s来到路飞购物商城!" % username)
26         else:
27             print("您的账号或密码错误,请重新输入!")
28             continue
29     else:
30         print("没有此用户,联系管理员创建!")
31         continue
32     while run_flag:
33         if data.get('salary') != 0:
34             salary = data.get('salary')
35             print("您的工资还剩余:\033[1;31;m%s\033[0m" % salary)
36         else:
37             salary = input("请输入您的工资:").strip()
38             if salary.isdigit():    # 判断输入的是不是数字,是数字的话就将输入的转为int类型
39                 salary = int(salary)
40             else:
41                 print("输入有误,输入的值应为数字!")
42                 continue
43         while run_flag:
44             for index, i in enumerate(goods):   # enumerate枚举,打印列表中的序号和值
45                 print(index, i.get("name"), i.get("price"))
46             chioce = input("请输入您想购买的商品序号:").strip()
47             if chioce.isdigit():
48                 chioce = int(chioce)
49                 if chioce < len(goods) and chioce >= 0:
50                     user_chioce = goods[chioce]
51                     if salary < user_chioce.get('price'):
52                         print("您的余额不足!")
53                         continue
54                     else:
55                         salary -= user_chioce.get('price')
56                         # shopping_cart.append(user_chioce)
57                         if user_chioce.get('name') not in data.get('shopping_cart'):    # 初始化字典
58                             data.get('shopping_cart')[user_chioce.get('name')] = {'count': 0,'sub_total': 0}
59                         data.get('shopping_cart')[user_chioce.get('name')]['count'] += 1
60                         data.get('shopping_cart')[user_chioce.get('name')]['sub_total'] += \
61                                                                                         user_chioce.get('price')
62                         print("已将商品 \033[1;32;m%s\033[0m 加入购物车!"%(user_chioce.get('name')))
63                         print("剩余余额为:\033[1;32;m%s\033[0m" % salary)
64                 else:
65                     print("对不起,没有此商品!")
66             elif chioce.lower() == "q":  # 判断输入是否是退出,不区分大小写
67                 if len(data.get('shopping_cart')) > 0:
68                     print("已购买商品".center(50, "-"))
69                     for i in data.get('shopping_cart'):
70                         print(i, data.get('shopping_cart')[i].get('count'),
71                               data.get('shopping_cart')[i].get('sub_total'))
72                     print("您的工资还剩余:\033[1;31;m%s\033[0m" % salary)
73                     data['salary'] = salary
74                     with open(account_file, 'w', encoding='utf-8') as f:
75                         f.write(str(data))
76                     run_flag = False
77                 else:
78                     exit("系统正在退出。。。")
79             elif chioce.lower() == 'h':  # 查找历史购买记录
80                 print("已购买商品".center(50, "-"))
81                 for i in data.get('shopping_cart'):
82                     print(i, data.get('shopping_cart')[i].get('count'),
83                           data.get('shopping_cart')[i].get('sub_total'))
84                 print("-".center(50, "-"))
85             else:
86                 print("输入有误!")

猜你喜欢

转载自www.cnblogs.com/mifengwei/p/9121259.html