Python学习之购物车

实现功能:

  1. 程序启动,提示用户输入用户名和密码,程序读取余额文件last_salary.txt内容(文件不存在则自动创建),若文件内容为空则提示“首次登录,请输入工资”;
  2. 用户可以输入商品编号进行购买;
  3. 用户选择商品后,自动计算总价,若总价超过账户余额salary,则提示余额不足;若总价未超过余额,则自动扣除;
  4. 用户可在购买过程中随时退出“q”;
  5. 关键信息高亮显示;
  6. 用户退出时,余额信息存入文件last_salary.txt,购买商品信息存入文件last_bucket.txt,文件不存在则自动创建;
  7. 用户再次登录时,读取并显示当前账户余额信息;
  8. 用户可在购买过程中输入“h”查询历史消费信息;
  9. 支持多个用户;
  10. 支持显示当前购物车商品数量;
  11. 当购物车为空,退出时显示提示信息。

示例代码:

 1 # -*- coding: utf-8 -*-
 2 
 3 import os
 4 from datetime import datetime
 5 
 6 goods = [
 7 {"name": "电脑", "price": 1999},
 8 {"name": "鼠标", "price": 10},
 9 {"name": "游艇", "price": 20},
10 {"name": "美女", "price": 998},
11 ]
12 
13 now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')      #获取当前时间
14 bucket =  []        #定义空列表存储购买的商品
15 price_list = {}     #将商品及其价格以“键值对”形式存入字典
16 total_price = item_price = 0
17 exit_flag = False
18 user_info = {'admin':'admin','alex':'123456'}       #定义用户名密码
19 
20 #生成商品-价格字典
21 for i in goods:
22     a = list(i.values())
23     price_list.setdefault(a[0],a[1])
24 
25 #生成商品名称列表
26 product_list = list(price_list)
27 
28 #开始
29 while not exit_flag:
30     username = input("用户名:").strip()
31     if username in user_info:
32         while not exit_flag:
33             userpasswd = input("密码:").strip()
34             if userpasswd == user_info.get(username):
35                 if not os.path.isfile(username + '_last_salary.txt'):       #判断username + '_last_salary.txt'是否存在,不存在则创建,存在则读取文件内容
36                     with open(username + '_last_salary.txt', 'w+', encoding='utf-8') as f:
37                         s = f.read()
38                 else:
39                     with open(username + '_last_salary.txt','r',encoding= 'utf-8') as f:      #若username + '_last_salary.txt'文件存在,则读取内容
40                         s = f.read()
41                 if len(s):          #如果username + '_last_salary.txt'不存在或为空,则表示用户首次登录,要求输入工资
42                     salary = int(s)
43                     print("\033[1;31;m*欢迎回来!账户余额:%d\033[0m " % salary)
44                 else:
45                     while True:
46                         salary = input("\033[1;31;m*首次登录,请输入工资:\033[0m").strip()     #首次登陆需输入工资
47                         if salary.isdigit():
48                             salary = int(salary)
49                             break
50                         else:
51                             print("输入错误,请重试!")
52                 print("-------商品列表------")
53                 for n,i in enumerate(price_list):
54                     print(n,i,price_list[i])
55                 while not exit_flag:        #要求用户输入商品编号
56                     select = input("请选择商品:").strip()
57                     if select.isdigit() and int(select) < len(goods):       #判断输入的商品编号是否是数字,且在范围内
58                         select = int(select)
59                         p = product_list[select]
60                         item_price = price_list[p]
61                         total_price += item_price
62                         if salary < item_price:              #若余额小于所选商品价格,则提示余额不足
63                             print("\033[1;31;m余额不足!\033[0m")
64                             print(salary)
65                         else:                               #若余额大于或等于所选商品价格,则扣除相应该商品对应价格并加入购物车
66                             salary = salary - item_price
67                             bucket.append(p)
68                             print("\033[1;31;m \'%s\'已加入购物车! \033[0m" % p )
69                     elif select == 'q':                 #若用户输入q退出,则:打印已购买商品列表;打印账户余额;将余额和购买记录分别存入不同文件
70                         print("\033[1;31;m-------已购买商品-------\033[0m")
71                         if len(bucket):
72                             for n,p in enumerate(set(bucket)):
73                                 print(p,tuple(bucket).count(p))
74                         else:
75                             print("当前购物车为空!")
76                         print("\033[1;31;m-----------------------\033[0m")
77                         print("\033[1;31;m账户余额:%d\033[0m" % salary)
78                         with open(username + '_last_salary.txt','w',encoding= 'utf-8') as f1:
79                             f1.write(str(salary))               #将余额存入文件username + '_last_salary.txt'
80                         with open(username + '_last_bucket.txt','a+',encoding= 'utf-8') as f2:
81                             for i in bucket:                    #将消费记录存入文件username + '_last_bucket.txt',若文件不存在则创建,指定写入字符串编码为utf-8
82                                 f2.write(now + ' ' + i + '\n')
83                         exit_flag = True
84                     elif select == 'h':         #当用户输入'h',读取并打印历史消费信息
85                         print("--------历史购买商品-------")
86                         if os.path.isfile(username + '_last_bucket.txt'):
87                             with open(username + '_last_bucket.txt','r',encoding= 'utf-8') as f:
88                                 l = f.read()
89                                 print(l)
90                         else:
91                             with open(username + '_last_bucket.txt', 'w', encoding='utf-8') as f:
92                                 print("历史记录为空!")
93                     else:
94                         print("请输入商品编号!")
95                         continue
96             else:
97                 print("密码错误,请重试!")
98     else: print("用户不存在,请重试!")

代码写的有点冗余繁杂,后期再优化。

posted @ 2018-04-11 20:51  人道酬成  阅读(171)  评论(0编辑  收藏  举报