购物车程序二(模拟了用户登录,限次数三次)

 1 '''
 2 #作业二:请闭眼写出购物车程序
 3 goods = [
 4     {"name": "电脑", "price": 1999},
 5     {"name": "鼠标", "price": 10},
 6     {"name": "游艇", "price": 20},
 7     {"name": "美女", "price": 998},
 8 ]
 9 #需求:
10 用户名和密码存放于文件中,格式为:jack|123
11 启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
12 允许用户根据商品编号购买商品
13 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
14 可随时退出,退出时,打印已购买商品和余额
15 
16 '''
17 shopping_car = []
18 flag = False
19 num = 1
20 
21 while num < 4:
22     name = input("请输入用户名:")
23     password = int(input("请输入密码:"))
24     with open('msg.txt', encoding='utf-8') as f:
25         for line in f:
26             if name == line.split('|')[0] and password == int(line.split('|')[1]) :
27                 salary = int(input("请输入您的总资产:"))
28                 with open('goods.txt',encoding='utf-8') as g:
29                     i = 1
30                     goods = []
31                     for line in g:
32                         dic = eval(line)
33                         print('商品编号:',i , dic['name'],'----->',dic['price'])
34                         goods.append(dic)
35                         i += 1
36 
37                     while True:
38                         num = input('选择商品序列号[按q 退出]:')
39                         if num != 'q':
40                             num = int(num)
41                             if goods[num - 1]['price'] < salary:
42                                 salary = salary - goods[num - 1]['price']
43                                 shopping_car.append(goods[num - 1]['name'])
44                             else:
45                                 print("你的余额不足,请充值")
46                                 salary = input('输入充值额度[按q 退出]:')
47                                 if salary == 'q':
48                                     break
49                                 else:
50                                     salary = int(salary)
51                                 continue
52 
53                         else:
54                             print('谢谢惠顾')
55                             break
56                     print('你的余额:', salary)
57                     print('购买的商品:', shopping_car)
58 
59                     flag = True
60                     break
61             elif num < 3:
62                 print("输入有误,请重新输入!")
63             elif num == 3:
64                 print("刷新重试")
65         if flag:
66             break
67     num += 1

msg.txt: 
  jack|123

goods.txt

  
{"name": "电脑", "price": 1999}
{"name": "鼠标", "price": 10}
{"name": "游艇", "price": 20}
{"name": "美女", "price": 998}


posted @ 2018-03-27 22:15  JerryZao  阅读(255)  评论(0编辑  收藏  举报