野蛮猿人

导航

测试

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键退出时会将最新的消费记录更新到文件。

代码

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

 

posted on 2018-01-04 15:33  野蛮猿人  阅读(95)  评论(0)    收藏  举报