python模拟购物车流程_Python程序练习3--模拟购物车

1 #Author:Byron Li

2 #-*-coding:utf-8-*-

3

4 '''----------------------------------------------使用文件说明----------------------------------------------------------5 使用文件说明6 userlist.txt 存放用户账户信息文件,包括用户名、密码、登陆次数和余额7 ***_cost_record.txt 存放某用户***消费记录的文件,用户首次购买商品后创建,没有购买过商品的用户不会产生该文件8 ---------------------------------------------------------------------------------------------------------------------'''

9 importos10 importdatetime11

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 returnNone25

26 def get_balance(name): #获取用户余额数据

27 with open('userlist.txt', 'r',encoding='UTF-8') as f:28 line =f.readline()29 for line inf:30 if name ==line.split()[0]:31 return line.split()[3]32 print("用户%s不存在,无法获取其余额信息!"%name)33 returnFalse34

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 returnTrue47 print("用户%s不存在,无法更新其余额信息!" %name)48 returnFalse49

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 returnTrue57 else:58 print("您还没有任何历史消费记录!")59 returnFalse60

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 inshopping_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 inshopping_list:75 f.write("%-5s%+20s\n"%(product[0],str(product[1])))76 returnTrue77 else:78 print("您本次没有购买商品,不更新消费记录!")79 returnFalse80

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 iflogin_times:97 print('欢迎%s第%d次登陆!'.center(50,'*')%(username,login_times))98 if login_times==1:99 balance = input("请输入工资:") #第一次登陆输入账户资金

100 while(True):101 ifbalance.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 ifchoice.isdigit():114 if int(choice)==0: #查询历史消费记录

115 inquire_cost_record(username)116 elif int(choice)==1: #购买商品

117 while(True):118 for index,item inenumerate(product_list):119 print(index,item)120 choice=input("请输入商品编号购买商品:")121 ifchoice.isdigit():122 if int(choice)>=0 and int(choice)

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 inshopping_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() #主程序运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值