购物车流程的实现

购物车
1. 商品信息- 数量、单价、名称
2. 用户信息- 帐号、密码、余额
3. 用户可充值
4. 购物历史信息
5. 允许用户多次购买,每次可购买多件
6. 余额不足时进行提醒
7. 用户退出时 ,输出当次购物信息
8. 用户下次登陆时可查看购物历史
9. 商品列表分级显示

   使用的购物菜单数据,采用字典结构进行创建。

 1 {
 2     '服装': {
 3         '外套': {
 4             '皮衣': {
 5                 '加绒皮衣 2000',
 6                 '机车皮衣 1000',
 7                 '牛皮皮衣 1500',
 8                 '羊皮皮衣 1800',
 9             },
10             '风衣': {
11                 '立领风衣 500',
12                 '双层领风衣 800',
13             }
14         },
15         '西装': {
16             '休闲西装': {
17                 '韩版休闲西装 600',
18                 '欧美风休闲西装 500',
19             },
20             '宴会西装': {
21                 '修身燕尾服 1200',
22                 '宫廷装 1000',
23             },
24         },
25         '裤子': {
26             '休闲裤': {
27                 '修身休闲裤 300',
28                 '宽松休闲裤 280',
29             },
30             '牛仔裤': {
31                 '紧身牛仔裤 180',
32                 '镂空牛仔裤 230',
33             },
34         },
35     },
36     '家电': {
37         '电视': {
38             "液晶电视": {
39                 '32寸液晶电视 1400',
40                 '42寸液晶电视 2200',
41                 '55寸液晶电视 4500',
42             },
43             "网络电视": {
44                 '2K网络电视 1500',
45                 '4K网络电视 3200',
46                 '曲面网络电视 4600',
47             }
48         },
49         '空调': {
50             '挂壁式空调': {
51                 '冷暖型挂壁式空调 1600',
52                 '单冷型挂壁式空调 1800',
53             },
54             '柜式空调': {
55                 '2匹柜式空调 4000',
56                 '3匹柜式空调 6000',
57             },
58         },
59     },
60 }
shopping menu

该项目思路:

1、创建一个文件用来保存用户名和密码信息,每次用户注册和登录操作时从中读取和写入数据

2、创建另一个文件用来记录每个用户的购物信息以及个人账户信息,采用字典键值对的形式实现每个用户和信息的对应关系

3、利用函数实现每一个模块的功能,最后进行整合

4、商品分级显示可以参照三级菜单的实现原则+try...except...结构;博客链接 http://www.cnblogs.com/sl-swift/p/7808859.html

  1 import time
  2 #用户注册
  3 #user_shopping_info = {name:[account,history_info=[商品名,时间]],}
  4 def register():
  5     r_flag = True
  6     while True:
  7         new_user_name = input("请输入新账户名【返回R】:
<<<").strip()
  8         if not new_user_name:
  9             print('用户名不能为空!')
 10             continue
 11         if new_user_name.lower() == 'r':
 12             break
 13         new_user_pwd = input("请输入用户密码且不少于六位【返回R】:
<<<").strip()
 14         if new_user_pwd.lower() == 'r':
 15             break
 16         if len(new_user_pwd) < 6:
 17             print('密码长度小于6位!')
 18             continue
 19         with open("user_info",mode="r+",encoding="utf8") as f1:
 20             with open('user_shopping_info','r+',encoding='utf8') as f2:
 21                 f1.seek(0)
 22                 for line in f1:
 23                     if line.startswith("name:") and new_user_name in line: #判断是否已经有该用户
 24                         print("该用户已经被注册!")
 25                         r_flag = False
 26                         continue
 27                 if r_flag:
 28                     f1.write("
name:"+new_user_name+'	|password:'+new_user_pwd)
 29                     info_str = f2.read()
 30                     try:
 31                         user_shopping_info = eval(info_str)
 32                     except Exception:
 33                         user_shopping_info = {}
 34                     user_shopping_info[new_user_name] = [10000,[]]   #默认每个账户初始金额为10000
 35                     f2.seek(0)
 36                     f2.write(str(user_shopping_info))
 37                     print("新用户注册成功!")
 38                     break
 39 
 40 #用户登录
 41 def login():
 42     l_flag = False
 43     while True:
 44         user_name = input("请输入账户名【返回R】:
<<<").strip()
 45         if not user_name:
 46             print('用户名不能为空!')
 47             continue
 48         if user_name.lower() == 'r':
 49             break
 50         user_pwd = input("请输入用户密码【返回R】:
<<<").strip()
 51         if user_pwd == 'r':
 52             break
 53         with open("user_info",mode="r",encoding="utf8") as f_read:
 54             f_read.seek(0)
 55             for line in f_read:
 56                 #关键调试步骤
 57                 if line.startswith("name:") and user_name in line and line.strip().split(':')[-1] == user_pwd:
 58                     l_flag = True
 59                     break
 60         if l_flag:
 61             print('用户登录成功!')
 62             print('欢迎进入购物车界面'.center(19,'*'))
 63             switch(user_name)
 64             break
 65         else:
 66             print('用户名或者密码错误!')
 67 
 68 #购物历史信息查询
 69 def history_info(user_name):
 70     with open('user_shopping_info','r',encoding='utf8') as f:
 71         info_str = f.read()
 72         user_shopping_info = eval(info_str)
 73         count = 1
 74         print('您的历史购物记录如下:')
 75         for line in user_shopping_info[user_name][1]:
 76             if count % 2 == 1:
 77                 print(line,'日期:',end='')
 78                 count += 1
 79             else:
 80                 print(line)
 81                 count += 1
 82 
 83 #账户余额
 84 def search_balance(user_name):
 85     with open('user_shopping_info','r',encoding='utf8') as f:
 86         info_str = f.read()
 87         user_shopping_info = eval(info_str)
 88         balance = user_shopping_info[user_name][0]
 89         print('您的可用余额为:%s元'%balance)
 90     return balance
 91 #进行购物
 92 #user_shopping_info = {name:[account,history_info=[商品名,时间]],}
 93 def shopping(user_name):
 94     while True:
 95         balance = search_balance(user_name)
 96         with open("shopping menu", mode="r",encoding='utf8') as f:
 97             product_str = f.read()
 98             product_list = eval(product_str)
 99         current_layer = product_list
100         last_layer = []
101         while True:
102             for line in current_layer:
103                 print('33[33m'+ line +'33[37m')
104             choice = input('请输入要购买的物品【退回上一层B】【退出Q】:
>>>>').strip()
105             if not choice: continue
106             if choice == 'q':  #退出循环
107                 print("退出购物!")
108                 return
109             elif choice.lower() == 'b':  # 退回到上一层目录
110                 if last_layer:
111                     current_layer = last_layer[-1]
112                     last_layer.pop()
113                     continue
114                 else:
115                     print('当前处在起始层!')
116             elif choice in current_layer:
117                 try:
118                     last_layer.append(current_layer)  # 采用列表里面嵌套字典的结果!
119                     current_layer = current_layer[choice]  # 进到下一层
120                 except Exception:
121                     ins_buy = input('是否要购买该商品【是Y否N】').strip()
122                     if ins_buy.lower() == 'y':
123                         goods_name = choice.split(' ')[0]
124                         print(goods_name)
125                         print(type(goods_name))
126                         goods_price = choice.split(' ')[1]
127                         tim = str(time.strftime('%Y-%m-%d %X'))
128                         break
129                     else:
130                         continue
131             else:
132                 print('您输入的信息有误,请重新选择!')
133         if int(balance) >= int(goods_price):
134             bal = int(balance) - int(goods_price)
135             with open('user_shopping_info','r+',encoding='utf8') as f:
136                 info_str = f.read()
137                 user_shopping_info = eval(info_str)
138                 user_shopping_info[user_name][0] = bal
139                 user_shopping_info[user_name][1].append(goods_name)
140                 user_shopping_info[user_name][1].append(tim)
141                 f.seek(0)
142                 f.write(str(user_shopping_info))
143             print('商品已经购买!')
144         else:
145             print('您的账户余额不足,请先进行充值!')
146 
147 #账户充值
148 def recharge(user_name):
149     with open('user_shopping_info','r+',encoding='utf8') as f:
150         info_str = f.read()
151         user_shopping_info = eval(info_str)
152         balance = user_shopping_info[user_name][0]
153         print('您的可用余额为:%s元'%balance)
154         while True:
155             recharge = input('请选择要充值的金额:'
156                              '
	【1】500'
157                              '
	【2】1000'
158                              '
	【3】2000'
159                              '
	【4】5000'
160                              '
	【5】自选金额'
161                              '
	【Q】退出'
162                              '
>>>').strip()
163             if recharge.lower() == 'q':
164                 break
165             if recharge == '1':
166                 rec = '500'
167             elif recharge == '2':
168                 rec = '1000'
169             elif recharge == '3':
170                 rec = '2000'
171             elif recharge == '4':
172                 rec = '5000'
173             elif recharge == '5':
174                 rec = input('请输入金额:').strip()
175                 if not rec.isdigit():
176                     print('您输入的金额有误,请重新开始操作!')
177                     continue
178             else:
179                 print('您选择的操作有误,请重新选择!')
180                 continue
181             balance = int(balance) + int(rec)
182             print('充值成功,您可以继续充值或退出!')
183         user_shopping_info[user_name][0] = balance
184         f.seek(0)
185         f.write(str(user_shopping_info))
186 
187 #操作选择界面
188 def switch(user_name):
189     while True:
190         case = input('请选择您要进行的操作:'
191                      '
	1.购物历史信息查询'
192                      '
	2.账户余额'
193                      '
	3.开始购物'
194                      '
	4.账户充值'
195                      '
	Q.退出'
196                      '
>>>').strip()
197         if case.lower() == 'q':
198             history_info(user_name)
199             print('成功退出购物车!')
200             break
201         elif case == '1':
202             history_info(user_name)
203         elif case == '2':
204             search_balance(user_name)
205         elif case == '3':
206             shopping(user_name)
207         elif case == '4':
208             recharge(user_name)
209         else:
210             print('您输入的指令有误,请重新输入!')
211             continue
212 
213 
214 if __name__ == '__main__':
215     while True:
216         choice = input("登陆L 注册R 退出Q:
<<<<").strip()
217         if choice.lower() == 'q':
218             print("欢迎下次光临!")
219             exit()
220         elif choice.lower() == 'l':
221             login()
222         elif choice.lower() =='r':
223             register()
224         else:
225             print('请输入正确的操作指令!')
226             continue

  通过该项目掌握了对文件的操作,包括写入和读取数据的注意事项,字符编码很重要!!!

在写程序流时什么时候该用到循环,什么时候进行判断都很重要。在函数的调用时,函数内部存在循环时,continue 进行下一次循环;break 跳出循环;return 直接退出该函数并且可以具有返回值。

再一次体会到字典在保存和调用数据时非常给力,程序中函数相互调用时需要传入关键性参数,本项目的关键参数是每一个登录后的用户名。

原文地址:https://www.cnblogs.com/sl-swift/p/7810157.html