前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >一个简单的购物商城,记录一下。

一个简单的购物商城,记录一下。

作者头像
py3study
发布2020-01-17 15:58:50
9200
发布2020-01-17 15:58:50
举报
文章被收录于专栏:python3python3
代码语言:javascript
复制
  1 #!/usr/bin/env python3
  2 Menu = {
  3     '电器':{
  4         '电视':{'索尼':'¥2999','康佳':'¥3999','飞利浦':'¥4999','购物车':'购物车','返回':'返回','退出':'退出'},
  5         '洗衣机':{'美的':'¥999','海尔':'¥1099','奥克斯':'¥1599','购物车':'购物车','返回':'返回','退出':'退出'},
  6         '中央空调':{'格力':'¥5699','日立':'¥18999','海信':'¥28999','购物车':'购物车','返回':'返回','退出':'退出'},
  7         '购物车':'购物车',
  8         '返回':'返回',
  9         '退出':'退出'
 10         },
 11     '数码产品':{
 12         '手机':{'苹果':'¥12999','小米':'¥3299','华为':'4299','购物车':'购物车','返回':'返回','退出':'退出'},
 13         '电脑':{'联想':'¥6999','戴尔':'¥8999','惠普':'¥7999','购物车':'购物车','返回':'返回','退出':'退出'},
 14         '摄影机':{'索尼相机':'¥19999','佳能':'¥1999','尼康':'¥6999','购物车':'购物车','返回':'返回','退出':'退出'},
 15         '购物车': '购物车',
 16         '返回':'返回',
 17         '退出':'退出'
 18         },
 19     '服装':{
 20         '鞋子':{'阿迪':'¥699','耐克':'¥599','李宁':'¥499','购物车':'购物车','返回':'返回','退出':'退出'},
 21         '衣服':{'七匹狼':'¥689','花花公子':'¥109','美特斯邦威':'¥209','购物车':'购物车','返回':'返回','退出':'退出'},
 22         '裤子':{'森马':'¥119','班尼路':'¥229','佐丹奴':'¥339','购物车':'购物车','返回':'返回','退出':'退出'},
 23         '购物车': '购物车',
 24         '返回':'返回',
 25         '退出':'退出'
 26         },
 27     '购物车':'购物车',
 28     '退出':'退出',
 29     }
 30 import time                                                                         #时间模块
 31 local_time = time.strftime('%Y{y}%m{m}%d{d} %H:%M:%S').format(y='年',m='月',d='日')    #定义一个时间格式
 32 
 33 
 34 def black_list():                                              #打开文件写入黑名单函数
 35     with open("black_list", "a") as black:
 36         black.write('\n'+user_input.strip())                  #将变量user_input写到文件中,\n为换行
 37 
 38 def lis():                                                          #显示购物车空函数
 39     print('您的购物车里什么都没有哦,快去选购吧!\n'
 40           '请输入%s或%s' % (previous, sign_out))
 41     for i in enumerate(lis_previous_sign_out, 1):                   #循环将列表中元素前加序号,从1开始
 42         print(i[0], i[1])                                           #打印元祖i的第一个和第二个元素
 43         dic_previous_sign_out[str(i[0])] = i[1]                     #循环将i的第一个元素加为字典中keys,第二个元素为values
 44 
 45 def exit():                                                         #结算退出函数
 46     ye = float(balance.strip('¥')) - float(sum(js_list))            #浮点计算,float为浮点,这里strip用来去掉字符串的符号,
 47     # sum()求和函数,这里用来计算列表js_list中所有元素的总和,js_list中为每个商品购买的总价
 48     if ye >= 0:                                                 #余额大于等于0
 49         while True:
 50             shopping = input('继续购物y或者结算退出商城n,输入y or n:').strip()
 51             if len(shopping) == 0:
 52                 print('输入不能为空,请重新输入!')
 53                 continue
 54             if shopping == 'y':
 55                 return False                                #返回False
 56             if shopping == 'n':
 57                 print('本次购物总计消费¥%s元,余额:¥%s元' % (float(sum(js_list)), ye))
 58                 print('欢迎下次购买,'
 59                       '用户%s退出商城!'
 60                       '%s' % (user_input, local_time))
 61                 return True
 62             else:
 63                 print('输入有误,请重新输入!')
 64                 continue
 65     else:
 66         print('余额不足请充值')
 67         return True
 68 
 69 def js_Settlement():                                        #结算函数
 70     while True:
 71         settlement = input('继续购物y或者结算n,输入%s/%s:' % ('y', 'n')).strip()
 72         if settlement == 'y':
 73             continue_flag = True
 74             break
 75         elif len(settlement) == 0:
 76             print('输入不能为空')
 77             continue
 78         elif settlement == 'n':
 79             for i in enumerate(Shopping_Cart.items(), 1):
 80                 # print(i)  i = (1:(索尼:{¥2999:[1,]}))
 81                 sp = i[1][0]                                        #i[1]=(索尼:{¥2999:[1,]}) i[1][0]=索尼
 82                 dj = list(i[1][1])[0]                               #i[1][1]={¥2999:[1,]},list(i[1][1])=(¥2999:[1,]),
 83                 # list(i[1][1])[0]=¥2999
 84                 sl = i[1][1][list(i[1][1])[0]].count(1) #i[1][1]={¥2999:[1,]},list(i[1][1])[0]=¥2999,
 85                 # i[1][1][list(i[1][1])[0]]=字典{¥2999:[1,]}取keys¥2999得到values[1],count(1)列表计算方法,统计列表中元素1有多少个
 86                 zj = int(dj.strip('¥')) * sl    #¥2999用strip去掉符号¥,乘以sl
 87                 js_list.append(zj)              #将zj用append方法追加到列表js_list中
 88                 print('%s 商品:%s 单价:%s 数量:%s 总价:%s' % (i[0], sp, dj, sl, zj))
 89             while True:
 90                 settlement = input('确认结算,确认y或者退出商城n,输入y or n:')
 91                 ye = float(balance.strip('¥')) - float(sum(js_list)) #浮点计算,sum(js_list)为列表js_list所有元素总和
 92                 print('本次购物总计消费¥%s元' % (float(sum(js_list))))
 93                 if settlement == 'y':
 94                     if exit():                              #判断函数exit()返回True
 95                         return True
 96                     else:
 97                         return False
 98                 if settlement == 'n':
 99                     return False
100             # if break_flag == True:
101             #     break
102         else:
103             print('输入有误,请输入y/n')
104             continue
105 
106 def shopping_cart():
107     if Shopping_Cart:
108         js_Settlement()
109     else:
110         while True:
111             lis()  # 调用函数lis()
112             user_choice = input('输入编号:').strip()
113             if user_choice == list(dic_previous_sign_out)[0]:
114                 return True
115             elif user_choice == list(dic_previous_sign_out)[1]:
116                 return False
117             elif len(user_choice) == 0:
118                 print('输入不能为空!!!')
119                 continue
120             else:
121                 print('输入有误,请重新输入!!!')
122                 continue
123 
124 with open('user_passwd', 'r') as f:                             #打开用户密码文件
125     user = dict(line.strip().split(":") for line in f if line)#将文件内容转换为字典
126 
127 passwd_error = []                                             #创建密码错误列表,密码错误一次将用户写入列表
128 user_does_not_exist = []                                      #创建不存在用户列表,不存在用户写入列表
129 Shopping_Cart = {}                                             #购物车空字典
130 dic_menu = {}                                                   #商品展示第一级空字典
131 dic_class = {}                                                  #商品展示第二级空字典
132 dic_commodity = {}
133 lis_previous_sign_out = ['返回商城','退出商城']                           #购物车中列表
134 dic_previous_sign_out = {}                                       #购物车中空字典
135 balance = '¥100000.00'
136 break_flag = False                                            #默认设置为False,用来退出多层循环
137 continue_flag = False                                          #默认设置为False,用来退出当前循环
138 previous = '返回商城'
139 sign_out = '退出商城'
140 js_list = []                                            #每个商品的总价写入这个列表,商品*数量
141 
142 for i in range(10):                                             #循环10次
143     user_input = input("Name:").strip()                         #输入账号,strip去除两侧空格
144     user_passwd = input("Passwd:").strip()                      #输入密码,strip去除两侧空格
145     with open("black_list","r") as black:                       #打开黑名单文件
146         for line in black:
147             if user_input == line.strip():                         #判断用户是否在黑名单中
148                 Tips = '账户%s被锁定,请与管理员联系!'%user_input      #定义字符串,将用户输入变量带入字符串,%s代替用户输入
149                 print(Tips.center(30,'*'))                          #字符串center方法,字符串居中,30为总长度,空白处用*代替
150                 break_flag = True                                   #将break_flag的值重新定义
151                 break                                               #退出循环
152         if break_flag == True:                                      #判断break_flag的值是否为True
153             break
154         if len(user_input) == 0 or len(user_passwd) == 0:      #判断用户输入是否为空格
155             Tips = '用户名或密码不能为空!'
156             print(Tips.center(30,'*'))
157             continue                                         #退出本次循环
158     if user_input in user and user[user_input] == user_passwd:#判断用户名和密码是否一致
159         Tips = '''
160         %s 欢迎用户%s登录商城'''%(local_time,user_input)
161         print(Tips.strip())                     #格式化输出%s来代替变量
162         msg = '''
163         用户:%s   账户余额:%s
164         '''%(user_input,balance)
165         print(msg.strip())
166         while True:
167             for i in enumerate(Menu, 1):                                #将字典第一级的kyes打印出来并加上序号,从1开始
168                 print(i[0],i[1])                                        #i为元祖,这里循环打印元祖的第一个元素和第二个元素
169                 dic_menu[str(i[0])] = i[1]                              #循环将i的第一个元素写到字典dic_menu中为keys,
170                 # 第二个元素写到字典中为vlaues。
171             user_choice_1 = input('请选择商品分类或退出:').strip()
172             if user_choice_1 == list(dic_menu)[-1]:
173                 break
174             elif user_choice_1 == list(dic_menu)[-2]:
175                 if shopping_cart():
176                     continue
177                 else:
178                     break_flag = True
179                     break
180             elif len(user_choice_1) == 0:
181                 print('输入不能为空!!!')
182                 continue
183             elif user_choice_1 in list(dic_menu)[0:3]:              #判断用户输入是否在列表的0-3,0包含0,3为小于3
184                 while True:
185                     for i in enumerate((Menu[dic_menu[user_choice_1]]), 1):
186                         print(i[0], i[1])
187                         dic_class[str(i[0])] = i[1]
188                     user_choice_2 = input('请选择商品:').strip()
189                     if user_choice_2 == list(dic_class)[-1]:
190                         break_flag = True
191                         break
192                     elif user_choice_2 == list(dic_class)[-2]:
193                         continue_flag = True
194                         break
195                     elif user_choice_2 == list(dic_class)[-3]:
196                         if shopping_cart():             #注意:判断函数返回值会执行函数,这里不需要单独在执行函数,否则会重复执行
197                             continue
198                         else:
199                             break_flag = True
200                             break
201                     elif len(user_choice_2) == 0:
202                         print('输入不能为空!!!')
203                         continue
204                     elif user_choice_2 in list(dic_class)[0:3]:         #判断用户输入是否在列表的0-3,0包含0,3为小于3
205                         commodity = Menu[dic_menu[user_choice_1]][dic_class[user_choice_2]]
206                         while True:
207                             for i in enumerate(commodity.items(),1):
208                                 if i[0] < 4:                            #enumerate方法为字典前添加序号,添加后为元祖:(1,(索尼:¥2999))
209                                     # 循环元祖,取元祖第一个元素比较,小于4输出
210                                     print(i[0], i[1][0], ':', i[1][1])#格式化输出,例:(1,(索尼:¥2999))为i,i[0]为1,i[1]为(索尼:¥2999),
211                                     # i[1][0]为索尼,i[1][1]为¥2999
212                                 elif i[0] >= 4:
213                                     print(i[0], i[1][0])
214                                 dic_commodity[str(i[0])] = i[1][0]
215                             user_choice_3 = input('请选择购买商品编号:').strip()
216                             if user_choice_3 == list(dic_commodity)[-1]:   #判断用户输入是否和列表最后一个元素相等,-1代表最后一个
217                                 break_flag = True
218                                 break
219                             elif user_choice_3 == list(dic_commodity)[-2]:
220                                 continue_flag = True
221                                 break
222                             elif user_choice_3 == list(dic_commodity)[-3]:
223                                 if shopping_cart():
224                                     continue
225                                 else:
226                                     break_flag = True
227                                     break
228                             elif len(user_choice_3) == 0:
229                                 print('输入不能为空!!!')
230                                 continue
231                             elif user_choice_3 in list(dic_commodity)[0:3]:
232                                 print('%s:%s已经加入购物车' % (dic_commodity[user_choice_3], commodity[dic_commodity[user_choice_3]]))
233                                 k = dic_commodity[user_choice_3]
234                                 v = commodity[dic_commodity[user_choice_3]] #commodity = Menu[dic_menu[user_choice_1]][dic_class[user_choice_2]]
235                                 if Shopping_Cart:                               #判断字典Shopping_Cart是否为空,这里非空
236                                     if k in Shopping_Cart and v == list(Shopping_Cart[k])[0]:
237                                         Shopping_Cart[k][v].append(1)           #Shopping_Cart[k][v]取出列表用append方法追加1进去
238                                     if k not in Shopping_Cart:
239                                         Shopping_Cart[k] = {v: [1, ]}
240                                 else:
241                                     Shopping_Cart[k] = {v:[1,]}
242                                 if js_Settlement():         #判断函数的返回值,为True
243                                     break_flag = True
244                                     break
245                                 else:                       #函数返回值False
246                                     continue
247                                 # if break_flag == True:
248                                 #     break
249                                 # if continue_flag == True:
250                                 #     continue
251                             else:
252                                 print('输入有误,请重新输入!!!')
253                                 continue
254                         if break_flag == True:
255                             break
256                         if continue_flag == True:
257                             continue
258                     else:
259                         print('输入有误,请重新输入!!!')
260                         continue
261                 if break_flag == True:
262                      break
263                 if continue_flag == True:
264                     continue
265 
266             else:
267                 print('输入有误,请重新输入!!!')
268                 continue
269         if break_flag == True:
270             break
271         if continue_flag == True:
272             continue
273     elif user_input not in user:                            #判断用户是都存在
274         Tips = '用户%s不存在,请重试!'%user_input
275         print(Tips.center(30,'*'))
276         user_does_not_exist.append(user_input)              #用户不存在就写入用户不存在列表中
277         if user_does_not_exist.count(user_input) == 5:      #统计用户不在列表中不存在的用户次数,超过5次锁定
278             Tips = '尝试次数过多,账户%s锁定!'%user_input
279             print(Tips.center(30,'*'))
280             black_list()                                    #调用函数black_list
281             break
282     else:
283         Tips = '密码错误!'
284         print(Tips.center(30,'*'))
285         passwd_error.append(user_input)                     #将密码错误用户写入密码错误列表中
286         if passwd_error.count(user_input) == 3:             #统计密码错误用户是否超过3次
287             Tips = '密码错误3次,账户%s锁定,请联系管理员!'%user_input
288             print(Tips.center(30,'*'))
289             black_list()                                    #调用函数black_list
290             break
291         else:
292             continue                                       #退出当前循环
293 else:
294     Tips = '尝试次数过多!'
295     print(Tips.center(30,'*'))
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档