1 #!/usr/bin/env python
2 #coding=utf-8
3 import sys
4 #定义商品列表
5 goods =[
6 {"name":"电脑", "price": 1999},
7 {"name":"鼠标", "price": 10},
8 {"name":"游艇", "price": 20},
9 {"name":"美女", "price": 998},
10 {"name":"大宝剑","price":666}
11 ]
12 #定义一个余额列表
13 balance = []
14 #定义一个购物车列表
15 shopping_car = []
16 #简单定义用户名密码
17 username = ‘alex‘
18 password = ‘123456‘
19 #简易的登录验证
20 i = 0
21 while i < 3:
22 name = input("请输入用户名:").strip()
23 passwd = input("请输入密码:").strip()
24 if name == username and passwd == password:
25 print(‘=‘*15+‘欢迎登陆世纪联华‘+‘=‘*15)
26 break
27 else:
28 print("用户名或者密码错误,还剩%d次登陆机会!"%(2-i))
29 i += 1
30 else:
31 sys.exit("三次输入失败,退出...")
32 #打开余额文件,查看是否有余额,是则不提示输入工资
33 with open(‘balance_file‘,‘r‘,encoding=‘utf-8‘) as balance_f:
34 balance_list = balance_f.readlines()
35 if len(balance_list) == 0: #如若balance_file为空,提示输入工资并作为余额
36 salary = int(input("请输入你的工资:").strip())
37 balance.append(salary)
38 else: #balance_file余额,则将余额添加到余额列表
39 history_balance = int(balance_list[0].strip(‘\n‘))
40 balance.append(history_balance)
41 while True:
42 #打印商品列表
43 print(‘=‘*10+"本店有以下商品,欢迎采购"+‘=‘*10)
44 for g,good in enumerate(goods,1):
45 print("\033[1;31;0m%s. %s %s \033[0m"%(g,good["name"],good["price"]))
46 #获取用户输入
47 action = input("请选择购买的商品编号(退出请按q;查询历史购买记录请按f):").strip()
48 #商品购买
49 if action.isdigit(): #检测输入的字符串是否只由数字组成
50 action = int(action) #若字符串只有数字组成,将其转换成int类型
51 if action > 0 and action <= len(goods):#判断输入的商品编号是否在商品列表内
52 if balance[0] >= goods[action-1]["price"]:#判断余额是否充足
53 shopping_car.append(goods[action-1]) #记录购物车
54 history_data = goods[action-1]["name"]+‘:‘+ str(goods[action-1]["price"])+‘\n‘
55 with open(‘history_file‘,‘a‘,encoding=‘utf-8‘) as h_f: #将选购商品信息写入history_file作为历史清单
56 h_f.write(history_data)
57 balance[0] = balance[0] - goods[action-1]["price"] #余额扣款
58 print("\033[1;0m%s已购买成功!\033[0m"%(goods[action-1]["name"]))
59 else:
60 print("\033[1;0m余额已不足...\033[0m")
61 else:
62 print("\033[1;0m此商品不存在,请根据商品列表购买!\033[0m")
63 #用户退出
64 elif action == ‘q‘ or action == ‘Q‘:
65 if len(shopping_car) > 0:
66 print(‘=‘*15+"您已购买了以下商品:")
67 else:
68 print("您没有购买商品..")
69 for g,good in enumerate(shopping_car,1): #遍历购物车,打印购买商品
70 print("\033[1;35;0m%s. %s %s \033[0m"%(g,good["name"],good["price"]))
71 print("\033[1;0m您的余额为:%d,欢迎下次光临!"%(balance[0])) #打印余额
72 with open(‘balance_file‘,‘r+‘,encoding=‘utf-8‘) as b_f: #将余额覆盖到balance_file
73 b_f.write(str(balance[0])+‘\n‘)
74 sys.exit(0)
75 #查询历史消费记录
76 elif action == ‘f‘ or action == ‘F‘:
77 with open(‘history_file‘,‘r‘,encoding=‘utf-8‘) as h_f:
78 h_list = h_f.readlines() #逐行读取history_file
79 if len(h_list) == 0:
80 print("没有历史购买记录!")
81 else:
82 print("\033[1;0m以下为历史购买记录:\033[0m") #遍历h_list,打印历史清单
83 for i,h in enumerate(h_list,1):
84 (name,price) = h.strip(‘\n‘).split(":")
85 print("\033[1;35;0m%s. %s %s\033[0m"%(i,name,price))