1. 程式人生 > >第二周作業購物車程序

第二周作業購物車程序

iphone6 input 分享 images read author tin 指針 code

技術分享

#coding:utf-8
#Author:Mr Zhi
file_open = open(購物車用戶信息,r+,encoding="utf-8")  #購物車用戶信息文件保存著用戶名密碼和余額
f = str(file_open.read())
for line in f:
     file_str = str(f)
file_open_dict = eval(file_str) #轉換成字典(文件內容原先是字典)
username = input("輸入用戶名:")
password = input("輸入密碼:")
while True:
    if username in
file_open_dict: #判斷用戶名是否在購物車用戶信息文件中 if password in file_open_dict[username]: salary = int(file_open_dict[username][password]) print(‘‘‘\033[32;1m歡迎登錄,當前余額為%s\033[0m‘‘‘ % salary) break else: password = input("密碼錯誤,請重新輸入密碼") continue
else: password_salary = {} #定義密碼,工資空字典 salary_str = input("歡迎第一次登陸,請輸入工資:") salary =float(salary_str) #輸入的工資轉成數字 password_salary[password] = salary #密碼與數字對應 file_open_dict[username] = password_salary #用戶名和密碼工資對應 file_open.seek(0) #文件讀取到開頭 file_open.write(str(file_open_dict)) #
把用戶名密碼和工資寫到文件中 file_open.tell() #返回當前位置 break product_list = [ #購物清單 [iphone6, 5000], [bike, 800], [python books, 200], [bag, 300], [macbook pro, 9000], ] history_f = open(history,r+,encoding="utf-8") #打開history文件 f2 = str(history_f.read()) for line in f2: file_str2 = str(f2) history_line = eval(file_str2) if username not in history_line: history_line[username] = [] shoppinglist = history_line[username] shoppinglist_new = [] choice = input ("\033[35;1m是否需要查詢歷史購物記錄(y/n)\033[0m") #詢問是否查詢歷史記錄 if choice == "y" or choice =="Y": print("---歷史購物記錄---") print(shoppinglist) while True: print("---商品清單---") for index,item in enumerate(product_list): #對元組進行遍歷並加上索引 print(index,item) #輸出商品 choice = input("輸入商品編碼:") #choice = int(choice) if choice.isdigit(): choice = int(choice) if choice < len(product_list) and choice >= 0: p_item = product_list[int(choice)] #把商品賦值給p_item print(p_item) if p_item[1] <= salary: #判斷商品價格和工資的大小 shoppinglist_new.append(p_item) #把商品加到元組 salary -= p_item[1] #余額 = 工資 - 商品 print("\033[37;1m買了 %s 還剩下 %s 元\033[0m" % (p_item, salary)) else: print("你的余額不足") else: print("你選擇的編碼%無效" % choice) elif choice == "q" or choice =="Q": file_open_dict[username][password] = salary #工資給對應的用戶密碼位置 file_open.seek(0) file_open.write(str(file_open_dict)) #把余額寫到購物車用戶信息文件中 file_open.tell() print("----已購商品清單----") print(shoppinglist_new) # 打印清單 print("\033[31;1m你的余額:%s\033[0m" % salary) # 打印余額 shoppinglist.extend(shoppinglist_new) # 本次購物記錄追加到購物列表中 history_line[username] = shoppinglist # 購物列表和用戶名對應 history_f.seek(0) #移動文件讀取指針到開頭 history_f.write(str(history_line)) # 購物記錄寫入文件 history_f.tell() #返回文件的當前位置 break else: print("你選擇的編碼%無效" % choice)

第二周作業購物車程序