Python程式練習3--類比購物車,python3--
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.流程圖
4.代碼
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 break104 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 break156 else:157 print('使用者名稱或密碼錯誤,請重新輸入!')158 159 shopping_chart() #主程式運行View Code