【阶段性成果3-2】Python编写购物车程序优化-顾客入口

需求:

'''

1.商品信息存在文件里
2.已购商品、余额要写进文件
3.其他需求不变

'''
'''
文件存储格式:
iPhoneXR 6299
XiaoMi9 3299
丰田威驰 79800
Only春装 1199
佛跳墙 999
苹果 333
西瓜 111
荔枝 555
桂圆 888
橘子 666
菠萝 121
草莓 212
'''


正文:

 1 # Author:David Liu 
 2 # Be Happy!
 3 import time
 4 salary = int(input("请输入您的工资:"))
 5 dict={}
 6 file = open('C:/Users/David/Desktop/商品列表.txt','r').readlines()
 7 for i in file:
 8     (key, value) = i.strip().split(' ')  # 切片,再存入字典
 9     dict.setdefault(key, value)
10 for i in file:
11     print(file.index(i) + 1,i.strip())  # 自动显示序号
12 buy=[]
13 money=[]
14 while True:
15     file2 = open('C:/Users/David/Desktop/购物清单.txt','a+')
16     goods=(input("请输入您想购买的商品名称:"))
17     if goods in dict:
18         if salary>=int(dict[goods]):
19             print(goods,"购买成功!")
20 
21             salary = salary - int(dict[goods])
22             buy.append(goods)
23             money.append(salary)
24 
25             question=input("是否继续购买?y/n")
26             if question=='y':
27                 continue
28             else:
29                 file2.write('\n')
30                 file2.write((time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))).center(50, '-'))  # 格式化输出当前日期和时间
31                 file2.write('\n')
32                 file2.write('已购商品:\n')
33                 for i in buy:
34                     file2.write('\t')
35                     file2.write(i)
36                     file2.write('\n')
37                 file2.write('当前余额:\n')
38                 file2.write('\t')
39                 file2.write(str(salary)+'')
40                 break
41         else:
42             print("您的余额不足,无法购买!")
43             question2 = input("是否继续购买其他商品?y/n")
44             if question2=='y':
45                 continue
46             else:
47                 break
48     else:
49         print("不存在该商品!")
50 print('\n', "已退出!".center(50, '-'))

结语:

商品信息由商家表提供,并实现购物清单写入文件。

程序所用数据皆为虚构,仅供实验所用。

2019年3月8日

猜你喜欢

转载自www.cnblogs.com/David0207AlwaysHappy/p/10497161.html