一個很low的購物車系統還花了我一下午時間
阿新 • • 發佈:2017-08-23
num col enc 返回值 index rate 備份 [0 商品
購物車的要求
有一兩個入口
用戶入口:
1.商品信息存在文件裏
2.已購商品余額記錄
商家入口
2.可添加商品,修改商品
用戶入口
倆個文件一個product.txt商品信息 一個歷史購買數據
用戶輸入本想加一個判斷歷史購買是否由余額然後直接輸入余額 ,但是if判斷好像返回不了返回值
1 # Author:Zhiyu Su 2 3 shopping_list=[] 4 f=open(‘product.txt‘,‘r‘,encoding=‘utf-8‘) 5 product_list=eval(f.read()) 6 7 l = open(‘歷史購買數據.txt‘, ‘r‘, encoding=‘utf-8‘).read() 8 9 10 11 salary = l 12 print(‘以前購物余額‘,salary) 13 14 salary = input("input your salay") 15 if salary.isdigit():#字符串形式的數字返回為真 16 salary = int(salary) 17 while True: 18 for index,item in enumerate(product_list):#enumerate 取元素的下標 19 20 #print(product_list.index(item),item) 21 print(index,item) 22 user_choice = input("選擇》》》》》》》》") 23 if user_choice.isdigit(): 24 user_choice=int(user_choice) 25 if user_choice < len(product_list) and user_choice >=0: 26 p_item = product_list[user_choice]27 if p_item[1] <= salary:#買的起 28 shopping_list.append(p_item) 29 print(shopping_list) 30 salary-= p_item[1] 31 print("added%s into shopping cart your crent balance is \033[31;1m%s\033[0m" %(p_item,salary)) #字體紅色 \033[31;1m**\033[0m 32 else: 33 print("\033[41;1m你的余額只剩[%s]啦,還買個毛線\033[0m"%salary) 34 else: 35 print("不存在[%s]"% user_choice) 36 elif user_choice == ‘q‘: 37 print("-----------shopping list--------------") 38 for p in shopping_list: 39 print(p) 40 print("your current balance:",salary) 41 k = open(‘歷史購買數據.txt‘, ‘w‘, encoding=‘utf-8‘) 42 k.write(str(salary)) 43 k.write(str(p)) 44 k.close() 45 exit() 46 else: 47 print("sojdioj") 48 f.close()
商家入口
有待完善的地方:修改完畢之後保存兩個文件一個是使用文檔,一個是備份。文檔以w模式寫 而備份以追加模式寫再加每次存寫的日期 ,如果文檔丟失按最接的時間拷貝到使用文本裏(這裏配備時間可能需要用到正則 )
1 # Author:Zhiyu Su 2 3 4 5 6 f = open(‘product.txt‘,‘r‘,encoding=‘utf-8‘) 7 8 9 data = eval(f.read()) 10 f_new = open(‘product.txt‘,‘w‘,encoding=‘utf-8‘) 11 # for i in data: 12 # print(i) 13 14 for index,item in enumerate(data):#enumerate 取元素的下標 15 print(index,item) 16 Choice = input(‘你要修改商品按x你要添加商品按t>>>>‘) 17 if Choice ==‘x‘: 18 choice = int(input("選擇要修改的商品號》》》")) 19 if choice <len(data): 20 print(data[choice]) 21 choice2 = input(‘修改名稱按--m--還是修價格按--q-->>>‘) 22 if choice2 ==‘m‘: 23 choice3 = input("你要修改的商品名稱>>>>>") 24 data[choice][0]=choice3 25 print(data) 26 f_new.write(str(data)) 27 elif choice2 == ‘q‘: 28 choice4 = input("你要修改的商品名稱>>>>>") 29 data[choice][1] = choice4 30 print(data) 31 f_new.write(str(data)) 32 elif Choice == ‘t‘: #添加功能 33 App = input(‘商品名稱>>>>>>‘) 34 end = input(‘商品價格>>>>>>‘) 35 data.append([App,end]) 36 f_new.write(str(data)) 37 else: 38 print(‘兄弟只有t和x‘) 39 f.close() 40 f_new.close()
一個很low的購物車系統還花了我一下午時間