Python程序练习3--模拟购物车

1.功能简介

此程序模拟用户登陆商城后购买商品操作。可实现用户登陆、商品购买、历史消费记查询、余额和消费信息更新等功能。首次登陆输入初始账户资金,后续登陆则从文件获取上次消费后的余额,每次购买商品后会扣除相应金额并更新余额信息,退出时也会将余额和消费记录更新到文件以备后续查询。

 

2.实现方法

  • 架构:

本程序采用python语言编写,将各项任务进行分解并定义对应的函数来处理,从而使程序结构清晰明了。主要编写了六个函数: 
(1)login(name,password) 
用户登陆函数,实现用户名和密码验证,登陆成功则返回登陆次数。 
(2)get_balance(name) 
获取用户余额数据。 
(3)update_balance(name,balance) 
更新用户余额数据,当用户按q键退出时数据会更新到文件。 
(4)inquire_cost_record(name) 
查询用户历史消费记录。 
(5)update_cost_record(name,shopping_list) 
更新用户消费记录,当用户按q键退出时本次消费记录会更新到文件。 
(6)shopping_chart() 
主函数,完成人机交互,函数调用,各项功能的有序实现。

  • 主要操作:

(1)根据提示按数字键选择相应选项进行操作。 
(2)任意时刻按q键退出退出登陆,退出前会完成用户消费和余额信息更新。

  • 使用文件: 

    (1)userlist.txt 
    存放用户账户信息文件,包括用户名、密码、登陆次数和余额。每次用户登陆成功会更新该用户登陆次数,每次按q键退出时会更新余额信息。 
    (2)***_cost_record.txt 
    存放某用户***消费记录的文件,用户首次购买商品后创建,没有购买过商品的用户不会产生该文件。每次按q键退出时会将最新的消费记录更新到文件。
 

3.流程图

Python程序练习3--模拟购物车

4.代码

Python程序练习3--模拟购物车Python程序练习3--模拟购物车
  1 # Author:Byron Li
  2 #-*-coding:utf-8-*-
  3 
  4 '''----------------------------------------------使用文件说明----------------------------------------------------------
  5 使用文件说明
  6 userlist.txt         存放用户账户信息文件,包括用户名、密码、登陆次数和余额
  7 ***_cost_record.txt  存放某用户***消费记录的文件,用户首次购买商品后创建,没有购买过商品的用户不会产生该文件
  8 ---------------------------------------------------------------------------------------------------------------------'''
  9 import os
 10 import datetime
 11 
 12 def login(name,password):   #用户登陆,用户名和密码验证,登陆成功则返回登陆次数
 13     with open('userlist.txt', 'r+',encoding='UTF-8') as f:
 14         line = f.readline()
 15         while(line):
 16             pos=f.tell()
 17             line=f.readline()
 18             if [name,password] == line.split()[0:2]:
 19                 times=int(line.split()[2])
 20                 line=line.replace(str(times).center(5,' '),str(times+1).center(5,' '))
 21                 f.seek(pos)
 22                 f.write(line)
 23                 return times+1
 24     return None
 25 
 26 def get_balance(name):   #获取用户余额数据
 27     with open('userlist.txt', 'r',encoding='UTF-8') as f:
 28         line = f.readline()
 29         for line in f:
 30             if name == line.split()[0]:
 31                 return line.split()[3]
 32     print("用户%s不存在,无法获取其余额信息!"%name)
 33     return False
 34 
 35 def update_balance(name,balance):    #更新用户余额数据
 36     with open('userlist.txt', 'r+',encoding='UTF-8') as f:
 37         line = f.readline()
 38         while(line):
 39             pos1=f.tell()
 40             line=f.readline()
 41             if name == line.split()[0]:
 42                 pos1=pos1+line.find(line.split()[2].center(5,' '))+5
 43                 pos2=f.tell()
 44                 f.seek(pos1)
 45                 f.write(str(balance).rjust(pos2-pos1-2,' '))
 46                 return True
 47     print("用户%s不存在,无法更新其余额信息!" % name)
 48     return False
 49 
 50 def inquire_cost_record(name):     #查询用户历史消费记录
 51     if os.path.isfile(''.join([name,'_cost_record.txt'])):
 52         with open(''.join([name,'_cost_record.txt']), 'r',encoding='UTF-8') as f:
 53             print("历史消费记录".center(40, '='))
 54             print(f.read())
 55             print("".center(46, '='))
 56             return True
 57     else:
 58         print("您还没有任何历史消费记录!")
 59         return False
 60 
 61 def update_cost_record(name,shopping_list):   #更新用户消费记录
 62     if len(shopping_list)>0:
 63         if not os.path.isfile(''.join([name, '_cost_record.txt'])):     #第一次创建时第一行标上“商品  价格”
 64             with open(''.join([name, '_cost_record.txt']), 'a',encoding='UTF-8') as f:
 65                 f.write("%-5s%+20s\n" % ('商品', '价格'))
 66                 f.write(''.join([datetime.datetime.now().strftime('%c'), ' 消费记录']).center(40,'-'))   #写入消费时间信息方便后续查询
 67                 f.write('\n')
 68                 for product in shopping_list:
 69                     f.write("%-5s%+20s\n"%(product[0],str(product[1])))
 70         else:
 71             with open(''.join([name, '_cost_record.txt']), 'a',encoding='UTF-8') as f:
 72                 f.write(''.join([datetime.datetime.now().strftime('%c'), ' 消费记录']).center(40, '-'))
 73                 f.write('\n')
 74                 for product in shopping_list:
 75                     f.write("%-5s%+20s\n"%(product[0],str(product[1])))
 76         return True
 77     else:
 78         print("您本次没有购买商品,不更新消费记录!")
 79         return False
 80 
 81 def shopping_chart():    #主函数,用户交互,函数调用,结果输出
 82     product_list=[
 83         ('Iphone',5000),
 84         ('自行车',600),
 85         ('联想电脑',7800),
 86         ('衬衫',350),
 87         ('洗衣机',1000),
 88         ('矿泉水',3),
 89         ('手表',12000)
 90     ]   #商店商品列表
 91     shopping_list=[]   #用户本次购买商品列表
 92     while(True):
 93         username = input("请输入用户名:")
 94         password = input("请输入密码:")
 95         login_times=login(username,password)   #查询输入用户名和密码是否正确,正确则返回登陆次数
 96         if login_times:
 97             print('欢迎%s第%d次登陆!'.center(50,'*')%(username,login_times))
 98             if login_times==1:
 99                 balance = input("请输入工资:")   #第一次登陆输入账户资金
100                 while(True):
101                     if balance.isdigit():
102                         balance=int(balance)
103                         break
104                     else:
105                         balance = input("输入工资有误,请重新输入:")
106             else:
107                 balance=int(get_balance(username))  #非第一次登陆从文件获取账户余额
108             while(True):
109                 print("请选择您要查询消费记录还是购买商品:")
110                 print("[0] 查询消费记录")
111                 print("[1] 购买商品")
112                 choice=input(">>>")
113                 if choice.isdigit():
114                     if int(choice)==0:                 #查询历史消费记录
115                         inquire_cost_record(username)
116                     elif int(choice)==1:               #购买商品
117                         while (True):
118                             for index,item in enumerate(product_list):
119                                 print(index,item)
120                             choice=input("请输入商品编号购买商品:")
121                             if choice.isdigit():
122                                 if int(choice)>=0 and int(choice)<len(product_list):
123                                     if int(product_list[int(choice)][1])<balance:   #检查余额是否充足,充足则商品购买成功
124                                         shopping_list.append(product_list[int(choice)])
125                                         balance = balance - int(product_list[int(choice)][1])
126                                         print("\033[31;1m%s\033[0m已加入购物车中,您的当前余额是\033[31;1m%s元\033[0m" %(product_list[int(choice)][0],balance))
127                                     else:
128                                         print("\033[41;1m您的余额只剩%s元,无法购买%s!\033[0m" %(balance,product_list[int(choice)][0]))
129                                 else:
130                                     print("输入编号错误,请重新输入!")
131                             elif choice=='q':      #退出账号登陆,退出前打印本次购买清单和余额信息,并更新到文件
132                                 if len(shopping_list)>0:
133                                     print("本次购买商品清单".center(50,'-'))
134                                     for product in shopping_list:
135                                         print("%-5s%+20s"%(product[0],str(product[1])))
136                                     print("".center(50, '-'))
137                                     print("您的余额:\033[31;1m%s元\033[0m"%balance)
138                                     update_cost_record(username,shopping_list)
139                                     update_balance(username, balance)
140                                     print("退出登陆!".center(50, '*'))
141                                     exit()
142                                 else:
143                                     print("您本次没有消费记录,欢迎下次购买!")
144                                     print("退出登陆!".center(50, '*'))
145                                     exit()
146                             else:
147                                 print("选项输入错误,请重新输入!")
148                     else:
149                         print("选项输入错误,请重新输入!")
150                 elif choice=='q':   #退出账号登陆
151                     print("退出登陆!".center(50, '*'))
152                     exit()
153                 else:
154                     print("选项输入错误,请重新输入!")
155             break
156         else:
157             print('用户名或密码错误,请重新输入!')
158 
159 shopping_chart() #主程序运行
View Code