Day2-ShoppingCart

本文介绍了一种购物车系统的实现方案,包括用户登录、商品浏览、购物车管理等功能,并提供了两种不同的实现方法,一种侧重于购物流程,另一种增加了用户注册功能。

实现购物车

1. 商品信息-数量、单价、名称

2. 用户信息-账号、密码、余额

3. 用户可充值

4. 购物历史信息

5. 允许用户多次购买,每次可购买多件

6. 余额不足时进行提醒

 

实现方法1

备注:同级目录下需有 user_info.txt

  1 #!/usr/local/env python
  2 # coding:utf-8
  3 import codecs, os, time
  4 ISOTIMEFORMAT="%Y-%m-%d %X"
  5 
  6 def user_login():
  7     global sUserName
  8     global iMoney
  9     count = 0
 10     cart = []
 11     wel_msg = u"Welcome to Shopping Mall".center(50, "-")
 12     cmd = input('''
 13     %s
 14     1:登录系统
 15     2:退出系统
 16     请输入您的操作:''' % wel_msg)
 17 
 18     if cmd.isdigit() and int(cmd) == 2:
 19         exit()
 20 
 21     elif cmd.isdigit() and int(cmd) == 1:
 22         match = False
 23         exist_user = False
 24         lock = False
 25         new_lines = []
 26         while count < 3:
 27             user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'r+', 'utf-8')
 28             username = input('请输入用户名:')
 29             lines = user_pass.readlines()
 30             new_lines = []
 31             for j in range(len(lines)):
 32                 line = lines[j]
 33                 new_lines.append(line)
 34                 user_file, password_file, lock_file, money_file = line.strip('\n').split()
 35                 if username == user_file:
 36                     if int(lock_file) == 1:
 37                         print('用户被锁定')
 38                         lock = True
 39                         new_lines = lines
 40                         break
 41                     exist_user = True
 42                     password = input('请输入密码:')
 43                     if password == password_file:
 44                         print('用户名和密码正确')
 45                         match = True
 46                         new_lines = lines
 47                         sUserName = user_file
 48                         iMoney = int(money_file)
 49                         if os.path.exists(os.path.join(os.path.dirname(__file__), '%s cart.txt' % sUserName)):
 50                             cart_file = codecs.open(os.path.join(os.path.dirname(__file__), '%s cart.txt' % sUserName), 'r+', 'utf-8')
 51                             cart = cart_file.readlines()
 52                         break
 53                     else:
 54                         i = 0
 55                         for i in range(2):
 56                             password = input('密码错误,请重新输入密码:')
 57                             if password == password_file:
 58                                 print('用户名和密码正确')
 59                                 match = True
 60                                 new_lines = lines
 61                                 sUserName = user_file
 62                                 iMoney = int(money_file)
 63                                 if os.path.exists(os.path.join(os.path.dirname(__file__), '%s cart.txt' % sUserName)):
 64                                     cart_file = codecs.open(os.path.join(os.path.dirname(__file__), '%s cart.txt' % sUserName), 'r+', 'utf-8')
 65                                     cart = cart_file.readlines()
 66                                 break
 67                         if i == 1:
 68                             print('密码输错3次,账户被锁定')
 69                             new_lines[j] = u"%s %s %d" % (user_file, password_file, 1)
 70 
 71             count += 1
 72             if lock:
 73                 user_pass.close()
 74                 if new_lines:
 75                     user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'username_file.txt'), 'wb', 'utf-8')
 76                     user_pass.writelines(new_lines)
 77                     user_pass.close()
 78                 exit()
 79             if not exist_user:
 80                 print('无效用户名')
 81                 continue
 82             if not match:
 83                 print('密码和用户名不匹配')
 84                 user_pass.close()
 85                 if new_lines:
 86                     user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'username_file.txt'), 'wb', 'utf-8')
 87                     user_pass.writelines(new_lines)
 88                     user_pass.close()
 89                 exit()
 90             else:
 91                 print('登录成功')
 92                 user_pass.close()
 93                 if new_lines:
 94                     user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'username_file.txt'), 'wb', 'utf-8')
 95                     user_pass.writelines(new_lines)
 96                     user_pass.close()
 97                 print('%s, 您的余额为: %d' % (sUserName, iMoney))
 98                 return sUserName, iMoney, cart
 99         print('重试超过3次,系统退出')
100         if new_lines:
101             user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'username_file.txt'), 'wb', 'utf-8')
102             user_pass.writelines(new_lines)
103             user_pass.close()
104 
105     else:
106         print('无效选项,程序已退出')
107         return
108 
109 def print_cart(cart, money):
110     new_cart = []
111     total_money = 0
112     for i in cart:
113         u_item, u_price, u_num, u_time = i.split("|")
114         flag = False
115         total_money += int(u_price) * int(u_num)
116         for j in range(len(new_cart)):
117             if new_cart[j].startswith(u_item):
118                 flag = True
119                 num = new_cart[j].split(",")[2]
120                 new_cart[j] = "%s, %s, %d, %s" % (u_item, u_price, int(u_num)+int(num), u_time)
121                 break
122         if not flag:
123             new_cart.append("%s, %s, %d, %s" % (u_item, u_price, int(u_num), u_time))
124     print("%s %s %s %s" % ("商品", "单价", "数量", "加入购物车时间"))
125     j = 1
126     for i in new_cart:
127         print(("%d - %s") % (j, i))
128         j += 1
129 
130     cmd_input = input("请输入选项:1:充值,2:删除购物车条目,3:结账,4:返回商城")
131     if cmd_input.isdigit() and int(cmd_input) == 4:
132         return cart, money
133 
134     elif cmd_input.isdigit() and int(cmd_input) == 1:
135         money_input = input("请输入充值金额")
136         money += int(money_input)
137         print("充值成功,余额为%d" % money)
138         return cart, money
139 
140     elif cmd_input.isdigit() and int(cmd_input) == 2:
141         item_input = input("请输入要删除的条目编号")
142         if int(item_input) - 1 < len(cart):
143             del cart[int(item_input) - 1]
144         else:
145             print("输入错误")
146         return cart, money
147 
148     elif cmd_input.isdigit() and int(cmd_input) == 3:
149         if total_money <= money:
150             print("购买成功")
151             money -= total_money
152             cart = []
153             print("余额为 %d" % money)
154         else:
155             print("余额不足")
156         return cart, money
157 
158     else:
159         print("请重新输入")
160 
161 
162 def display_list(username, money, cart):
163     category = {u"家电": {u"电视": ["45寸 2999", "55寸 3999", "60寸 4999"], u"空调": ["1匹 1999", "2匹 2999"]},
164                 u"服装": {u"上衣": ["短袖 299", "长袖 399"], u"裤子": ["短裤 299", "长裤 399"]},
165                 u"手机": {u"iPhone": ["16G 5288", "64G 6088"], u"小米": ["16G 999", "32G 1599"]},
166                 u"汽车": {u"BMW": ["320i 300000", "520i 400000"], u"BENZ": ["C200 300000", "E200, 400000"]}}
167 
168     b_quit = False
169     counter = 0
170     while True:
171         for key in category:
172             print(key)
173 
174         if counter > 2:
175             print("3次输入错误,程序退出")
176             break
177 
178         cat_name = input("输入品类, c查看购物车, q退出, b返回上一级目录:")
179         if cat_name == "q":
180             b_quit = True
181             print("退出查询")
182             break
183         elif cat_name == "b":
184             print("已是一级目录,无法返回上一级")
185             continue
186         elif cat_name == "c":
187             cart, money = print_cart(cart, money)
188             continue
189         if cat_name in category:
190             item_name = category[cat_name]
191             b_quit = False
192             while True:
193                 for key in item_name:
194                     print(key)
195                 item_input = input("输入物品名, c查看购物车, q退出, b返回上一级目录:")
196                 if item_input == "q":
197                     print("退出查询")
198                     b_quit = True
199                     break
200                 if item_input == "b":
201                     for key in category:
202                         print(key)
203                     break
204                 if item_input == "c":
205                     cart, money = print_cart(cart, money)
206                     break
207                 if item_input in item_name:
208                     name = category[cat_name][item_input]
209                     for i in name:
210                         print(i)
211                 else:
212                     print("输入有误,请重新输入:")
213                     continue
214                 b_or_q = input("输入型号购买, c查看购物车, q退出, b返回上一级目录:")
215                 if b_or_q == "b":
216                     continue
217                 elif b_or_q == "q":
218                     print("退出查询")
219                     b_quit = True
220                     break
221                 elif b_or_q == "c":
222                     cart, money = print_cart(cart, money)
223                     continue
224                 else:
225                     for i in category[cat_name][item_input]:
226                         if b_or_q == i.split()[0]:
227                             num_buy = input("请输入购买数量")
228                             if num_buy.isdigit():
229                                 print("已加入购物车")
230                                 cart.append("%s|%s|%s" % ("%s %s" % (item_input, i.replace(" ", "|")), num_buy, time.strftime(ISOTIMEFORMAT, time.localtime())))
231                             else:
232                                 print("输入有误,请重新输入")
233                                 break
234             if b_quit:
235                 save_cart(username, cart, money)
236                 print("系统退出")
237                 exit()
238         else:
239             print("输入有误,请重新输入:")
240             counter += 1
241             continue
242         if b_quit:
243             save_cart(username, cart, money)
244             print("系统退出")
245             exit()
246     if b_quit:
247         save_cart(username, cart, money)
248         print("系统退出")
249         exit()
250 
251 def save_cart(username, cart, money):
252     user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'username_file.txt'), 'r+', 'utf-8')
253     lines = user_pass.readlines()
254     new_lines = []
255     for j in range(len(lines)):
256         line = lines[j]
257         user_file, password_file, lock_file, money_file = line.strip('\n').split()
258         if username == user_file.strip():
259             line = ("%s %s %s %s\r\n" % (user_file, password_file, lock_file, money))
260         new_lines.append(line)
261     user_pass.close()
262     if new_lines:
263         user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'username_file.txt'), 'w', 'utf-8')
264         user_pass.writelines(new_lines)
265         user_pass.close()
266 
267     cart_file = codecs.open(os.path.join(os.path.dirname(__file__), '%s cart.txt' % username), 'w', 'utf-8')
268     sample_list = [line+'\r\n' for line in cart]
269     cart_file.writelines(sample_list)
270     cart_file.close()
271 
272 username, money, cart = (user_login())
273 display_list(username, money, cart)
方法1

 

实现方法2(新增注册功能)

备注: 同级目录下需有 user_info.txt,cart.txt

  1 import os,codecs
  2 import time
  3 import string
  4 ISOTIMEFORMAT="%Y-%m-%d %X"
  5 
  6 def inputTypeCast(sValue):
  7     if str.isdigit(sValue):
  8         sValue = int(sValue)
  9     return sValue
 10 
 11 def signUp():
 12     try:
 13         user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'r+', 'utf-8')
 14         lines = user_pass.readlines()
 15         useNameList = []
 16         for j in range(len(lines)):
 17             line = lines[j]
 18             #print(line)
 19             userName, passWord, lockFlag, accountBalance = line.strip('\n').split()
 20             useNameList.append(userName)
 21 
 22         signUpFlag = True
 23         while signUpFlag:
 24             sUserName = input("SingUp Here Buddy,Please Enter Your Name:")
 25             if sUserName in useNameList:
 26                 print ('This name has been used,please enter a new one')
 27                 continue
 28             elif sUserName == "q":
 29                 print('Thanks for your visiting')
 30                 exit()
 31                 user_pass.close()
 32 
 33             else:
 34                 passwordFlag = True
 35                 while passwordFlag:
 36                     sPassword = input('PleaseEnter Your Password:')
 37                     if sPassword == 'q':
 38                         print('Thanks for your visiting, bye')
 39                         exit()
 40                         user_pass.close()
 41                     else:
 42                         sConfirmPassword = input('Please Confirm Your Password:')
 43                         if sConfirmPassword == 'q':
 44                             print('Thanks for your visiting, bye')
 45                             exit()
 46                             user_pass.close()
 47                         else:
 48                             if sConfirmPassword != sPassword:
 49                                 print('Confirm password does not match,please re-enter your password')
 50                                 continue
 51                             else:
 52                                 bIncharge = input('Incharge Your Account Balance? (y/n) ')
 53                                 if bIncharge == 'q':
 54                                     lines = user_pass.writelines("\n%s %s %d %d" % (sUserName, sPassword, 0,0))
 55                                     print('Thanks for your registration, do not forget to incharge your account later.Re-login and happy shopping')
 56                                     exit()
 57                                     user_pass.close()
 58                                 elif bIncharge == 'n':
 59                                     lines = user_pass.writelines("\n%s %s %d %d" % (sUserName, sPassword, 0, 0))
 60                                     print('Thanks for your registration, do not forget to incharge your account later.Re-login and happy shopping')
 61                                     user_pass.close()
 62                                     signUpFlag = False
 63                                     break
 64 
 65                                 else:
 66                                     while True:
 67                                         dMoney = input('Please incharge your account with a numeber of..')
 68                                         if dMoney == "q":
 69                                             lines = user_pass.writelines("\n%s %s %d %d" % (sUserName, sPassword, 0,0))
 70                                             print('Thanks for your registration, do not forget to incharge your account later.Re-login and happy shopping')
 71                                             user_pass.close()
 72                                             exit()
 73                                         if int(dMoney) < 0:
 74                                             print('Negative number,please re-enter')
 75                                             continue
 76                                         else:
 77                                             lines = user_pass.writelines("\n%s %s %d %d" % (sUserName, sPassword, 0,int(dMoney)))
 78                                             print('Thanks for your registration,re-login and happy shopping!')
 79                                             passwordFlag = False
 80                                             signUpFlag = False
 81                                             user_pass.close()
 82                                             break
 83         return sUserName,int(dMoney)
 84     except EOFError as msg:
 85         print (msg)
 86         exit()
 87 
 88 def userLogin():
 89     global sUserName
 90     global iMoney
 91 
 92     count = 0
 93     match = False
 94     exist_user = False
 95     bLock = False
 96     while count < 3:
 97         user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'r+', 'utf-8')
 98         username = input('Please Enter Your Name:')
 99         lines = user_pass.readlines()
100         new_lines = []
101         for j in range(len(lines)):
102             line = lines[j]
103             new_lines.append(line)
104             #print(new_lines)
105             userName, passWord, lockFlag, accountBalance = line.strip('\n').split()
106             if username == userName:
107                 if int(lockFlag) == 1:
108                     bLock = True
109                     print('Your Account Has Been Locked')
110                     bLock = True
111                     new_lines = lines
112                     break
113                 exist_user = True
114                 password = input('Please Enter Your PassWord:')
115                 if password == passWord:
116                     str = 'Welcome %s!' % username
117                     print(str.center(40, "-"))
118                     match = True
119                     new_lines = lines
120                     sUserName = userName
121                     iMoney = int(accountBalance)
122                     break
123                 else:
124                     i = 0
125                     for i in range(2):
126                         password = input('Your PassWord is Incorrect,Please Re-Enter Your PassWord:')
127                         if password == passWord:
128                             print('UserName and PassWord Match!')
129                             match = True
130                             new_lines = lines
131                             sUserName = userName
132                             iMoney = int(accountBalance)
133                             break
134 
135                     if i == 1:
136                         print('Enter Incorrect PassWord for 3 Times.Your Account is Locked.Please Contact To The IST Help')
137                         new_lines[j] = u"%s %s %d %d\ny" % (userName, passWord, 1, int(accountBalance))
138 
139         count += 1
140         if bLock:
141             user_pass.close()
142             if new_lines:
143                 user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'wb', 'utf-8')
144                 user_pass.writelines(new_lines)
145                 user_pass.close()
146             exit()
147         if not exist_user:
148             print('No Valid UserName')
149             continue
150 
151         if not match:
152             print('UserName and PassWord Does Not Match')
153             user_pass.close()
154             if new_lines:
155                 user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'wb', 'utf-8')
156                 user_pass.writelines(new_lines)
157                 user_pass.close()
158             exit()
159         else:
160             print('Login Successfully')
161             user_pass.close()
162             if new_lines:
163                 user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'wb', 'utf-8')
164                 user_pass.writelines(new_lines)
165                 user_pass.close()
166             print('Dear %s, You Account Banlacne is: %d' % (sUserName, iMoney))
167             return {'UserName':sUserName, 'AccountBalance':iMoney}
168 
169     print('Repeat for 3 Times,System Quit!')
170     if new_lines:
171         user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'wb', 'utf-8')
172         user_pass.writelines(new_lines)
173         user_pass.close()
174     else:
175         print('No Valid Choices,System Quit!')
176         return
177 #
178 def print_cart():
179 #     new_cart = []
180 #     for i in cart:
181 #         u_item, u_price, u_num, u_time = i.split()
182 #         flag = False
183 #         for i in range(len(new_cart)):
184 #             if new_cart[i].beginswith(u_item):
185 #                 flag = True
186 #                 num = new_cart[i].split()[2]
187 #                 new_cart[i] = "%s, %s, %d, %s" % (u_item, u_price, u_num+num, u_time)
188 #                 break
189 #         if not flag:
190 #             new_cart.append("%s, %s, %d, %s" % (u_item, u_price, u_num, u_time))
191 #     print("%s %s %s %s" % ("商品", "单价", "数量", "加入购物车时间"))
192 #     for i in new_cart:
193 #         print(i)
194 
195     user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'cart.txt'), 'r+', 'utf-8')
196     lines = user_pass.readlines()
197     if lines == []:
198         return False
199     else:
200         for j in range(len(lines)):
201             line = lines[j]
202             print(line)
203 
204 
205 if __name__ == '__main__':
206 
207     category = {u"家电": {u"电视": ["45寸 2999", "55寸 3999", "60寸 4999"], u"空调": ["1匹 1999", "2匹 2999"]},
208                 u"服装": {u"上衣": ["短袖 299", "长袖 399"], u"裤子": ["短裤 299", "长裤 399"]},
209                 u"手机": {u"iPhone": ["16G 5288", "64G 6088"], u"小米": ["16G 999", "32G 1599"]},
210                 u"汽车": {u"BMW": ["320i 300000", "520i 400000"], u"BENZ": ["C200 300000", "E200, 400000"]}}
211     bLogin = False
212     str = " Welcome To My OnLine Mall "
213     print(str.center(40,"*"))
214     isLoginOrSignup = input("New to My Mall(y/n):")
215     if isLoginOrSignup =='y':
216         signUp()
217     elif isLoginOrSignup == 'n':
218         dict = userLogin()
219         userName = dict['UserName']
220         money = dict['AccountBalance']
221         bLogin = True
222     else:
223         print('No Valid Choice,System Quit!')
224 
225     if bLogin:
226         cart = []
227         for key in category:
228             print(key)
229         counter = 0
230         while True:
231             if counter > 2:
232                 print('3次输入错误,程序退出!')
233                 break
234             inputValue = input("输入品类, c查看购物车, q退出, b返回上一级目录:")
235             if inputValue == "q":
236                 print('Quit')
237                 break
238             elif inputValue == "b":
239                 print('It`s already the first level menu!')
240                 continue
241 
242             elif inputValue == "c":
243                 print_cart()
244                 continue
245 
246             if inputValue in category:
247                 item_name = category[inputValue]
248                 b_quit = False
249                 while True:
250                     for key in item_name:
251                         print(key)
252                     item_input = input("输入物品名, c查看购物车, q退出, b返回上一级目录:")
253                     if item_input == "q":
254                         print("欢迎下次再来")
255                         b_quit = True
256                         exit()
257                     if item_input == "b":
258                         for key in category:
259                             print(key)
260                         break
261                     if item_input == "c":
262                         print_cart()
263                         break
264                     if item_input in item_name:
265                         name = category[inputValue][item_input]
266                         for i in name:
267                             print(i)
268                     else:
269                         print("输入有人误,请重新输入:")
270                         continue
271                     b_or_q = input("输入型号购买, c查看购物车, q退出, b返回上一级目录:")
272                     if b_or_q == "b":
273                         continue
274                     elif b_or_q == "q":
275                         b_quit = True
276                         break
277                     elif b_or_q == "c":
278                         print_cart()
279                         continue
280 
281                     else:
282                         for i in category[inputValue][item_input]:
283                             if b_or_q == i.split()[0]:
284                                 num_buy = input("请输入购买数量")
285                                 if num_buy.isdigit():
286                                     print("已加入购物车")
287                                     cart.append("%s|%s|%s" % ("%s %s" % (item_input, i.replace(" ", "|")), num_buy,time.strftime(ISOTIMEFORMAT, time.localtime())))
288                                     user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'cart.txt'), 'r+','utf-8')
289                                     lines = user_pass.readlines()
290                                     if lines == []:
291                                         lines = user_pass.writelines("%s|%s|%s" % ("%s %s" % (item_input, i.replace(" ", "|")), num_buy,time.strftime(ISOTIMEFORMAT, time.localtime())))
292                                     else:
293                                         lines = user_pass.writelines("\n%s|%s|%s" % ("%s %s" % (item_input, i.replace(" ", "|")), num_buy,time.strftime(ISOTIMEFORMAT, time.localtime())))
294 
295                                     b_or_q = input("a:继续购物 | b: 结账 | q: 退出")
296                                     if b_or_q  == 'a':
297                                         break
298                                     elif b_or_q  == 'q':
299                                         print('欢迎您下次再来')
300                                         exit()
301                                     elif b_or_q  == 'b':
302                                         user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'cart.txt'), 'r+','utf-8')
303                                         lines = user_pass.readlines()
304                                         lprice = []
305                                         lQuanlity = []
306                                         for j in range(len(lines)):
307                                             line = lines[j]
308                                             print(line)
309                                             productName, productPrice, produtQuanlity, produtInChartTime = line.strip('\n').split('|')
310                                             lprice.append(productPrice)
311                                             lQuanlity.append(produtQuanlity)
312                                         #print(lprice)
313                                         #print(lQuanlity)
314                                         lMoney = []
315                                         for i in range(len(lprice)):
316                                             lMoney.append(int(lprice[i]) * int(lQuanlity[i]))
317                                         total_money = 0
318                                         for i in range(len(lMoney)):
319                                             total_money += lMoney[i]
320                                         #print(total_money)
321                                         # total_money = int(int(num_buy) * int(i.split()[1]))
322 
323 
324                                         if total_money <= money:
325                                             print("购买成功")
326                                             money -= total_money
327                                             #dictAccountInfo[userName] -= total_money
328                                             #money += int(moneyIncharge)
329                                             user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'r+', 'utf-8')
330                                             lines = user_pass.readlines()
331                                             dictAccountInfo = {}
332                                             for j in range(len(lines)):
333                                                 line = lines[j]
334                                                 print(line)
335                                                 userName, passWord, lockFlag, accountBalance = line.strip('\n').split()
336                                                 print(userName, accountBalance)
337                                                 dictAccountInfo.setdefault(userName, int(accountBalance))
338 
339 
340                                             dictAccountInfo[userName] -= int(total_money)
341                                             user_pass = codecs.open(
342                                                 os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'r+', 'utf-8')
343                                             lines = user_pass.readlines()
344                                             new_lines = []
345                                             for j in range(len(lines)):
346                                                 line = lines[j]
347                                                 new_lines.append(line)
348                                                 print(new_lines)
349                                                 username, passWord, lockFlag, accountBalance = line.strip('\n').split()
350                                                 if username == userName:
351                                                     new_lines[j] = u"%s %s %d %d\n" % (userName, passWord, int(lockFlag), int(dictAccountInfo[userName]))
352                                                 user_pass = codecs.open( os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'wb','utf-8')
353                                                 user_pass.writelines(new_lines)
354                                                 user_pass.close()
355 
356                                             print('Dear %s, 您的余额为: %d' % (userName, money))
357 
358                                             b_or_q = input("a:继续购物 q: 退出")
359                                             if b_or_q  == 'a':
360                                                 break
361                                             elif b_or_q == 'q':
362                                                 print('感谢您的光临,欢迎下次再来')
363                                                 exit()
364                                         else:
365                                             inCharge = input("余额不足,是否充值(y/n)?")
366                                             if inCharge == 'y':
367                                                 moneyIncharge = input("充入钱数: ")
368                                                 if moneyIncharge == "q":
369                                                     print('感谢您的光临,欢迎下次再来')
370                                                     exit()
371                                                 else:
372                                                     print('充值中。。。。')
373                                                     money += int(moneyIncharge)
374                                                     user_pass = codecs.open(os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'r+', 'utf-8')
375                                                     lines = user_pass.readlines()
376                                                     dictAccountInfo = {}
377                                                     for j in range(len(lines)):
378                                                         line = lines[j]
379                                                         print(line)
380                                                         userName, passWord, lockFlag, accountBalance = line.strip('\n').split()
381                                                         print(userName, accountBalance)
382                                                         dictAccountInfo.setdefault(userName, int(accountBalance))
383 
384                                                     dictAccountInfo[userName] += int(moneyIncharge)
385                                                     user_pass = codecs.open( os.path.join(os.path.dirname(__file__), 'user_info.txt'), 'r+','utf-8')
386                                                     lines = user_pass.readlines()
387                                                     new_lines = []
388                                                     for j in range(len(lines)):
389                                                         line = lines[j]
390                                                         new_lines.append(line)
391                                                         print(new_lines)
392                                                         username, passWord, lockFlag, accountBalance = line.strip('\n').split()
393                                                         if username == userName:
394                                                             new_lines[j] = u"%s %s %d %d\n" % (userName, passWord, int(lockFlag), int(dictAccountInfo[userName]))
395                                                         user_pass = codecs.open(os.path.join(os.path.dirname(__file__),'user_info.txt'), 'wb', 'utf-8')
396                                                         user_pass.writelines(new_lines)
397                                                         user_pass.close()
398 
399                                                     import time
400                                                     time.sleep(2)
401                                                     inChargeDone = input('充值完毕-(b:继续看看 | q:退出 )')
402                                                     if b_or_q == "b":
403                                                         break
404                                                     elif b_or_q == "q":
405                                                         print("欢迎下次再来")
406                                                         exit()
407 
408                                             elif inCharge == 'n':
409                                                 b_or_q = input('余额不足,无法购买-(b:继续看看 | q:退出)')
410                                                 if b_or_q =="b":
411                                                     break
412                                                 else:
413                                                     print("欢迎下次再来")
414                                                     exit()
415                                 else:
416                                     print("输入有误,请重新输入")
417                                     break
方法2

 

转载于:https://www.cnblogs.com/blademaster/p/5793820.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值