作業:購物商場
1、流程圖
2、初始化用戶賬號存儲文件
初始化存儲一個空的用戶賬號字典,保存到文件 user.pkl。執行如下代碼,即可初始化完成。
#!/usr/bin/env python # -*- coding:utf-8 -*- # Version:Python3.5.0 import pickle def init_user(): ''' 構造一個空的用戶字典,格式:{'用戶名':['密碼',賬號被鎖狀態,余額]} :return:None ''' # 先構造一個空字典,存儲用戶信息的文件 user.pkl user_dict = {} with open('user.pkl','wb') as f: pickle.dump(user_dict,f) print('init user info finish!') return None if __name__ == '__main__': init_user()
3、管理用戶賬號腳本
用來解鎖被鎖的賬號,以及可以修改賬號密碼
#!/usr/bin/env python # -*- coding:utf-8 -*- # Version:Python3.5.0 import pickle def unlock_user(): ''' 輸入解鎖的賬號,即可解鎖 :return: None ''' while True: # 輸入解鎖的賬號 user = input('Please input unlock the user: ').strip() # 判斷該賬號是否存在 if user in user_dict: # 把鎖狀態標志3 修改為 0 user_dict[user][1] = 0 with open('user.pkl','wb') as f: # 更新解鎖后的賬號信息,保存到user.pkl文件中 pickle.dump(user_dict,f) print('The %s unlock successfully!' % user) break else: print('Account does not exist, try again!') continue return None def change_pwd(): ''' 輸入要修改密碼的賬號,然后更新密碼 :return: None ''' while True: # 輸入解鎖的賬號 user = input('Please input the user of change password: ').strip() # 判斷該賬號是否存在 if user in user_dict: # 輸入新的密碼 new_pwd = input('Please input the %s new password: ' % user).strip() user_dict[user][0] = new_pwd with open('user.pkl','wb') as f: # 更新密碼后的賬號信息,保存到user.pkl文件中 pickle.dump(user_dict,f) print('The %s change password successfully!' % user) break else: print('Account does not exist, try again!') continue return None if __name__ == '__main__': # 設置界面功能選項列表 choose = [['1','unlock user'], ['2','change password'], ['3', 'exit']] # 讀取賬號文件 user.pkl with open('user.pkl','rb') as f: user_dict = pickle.load(f) while True: # 打印界面功能選項 print('=' * 50) for i in choose: for j in i: print(j, end= ' ') print('') input_choose = input('Please choose the index: ').strip() # 選擇解鎖功能 if input_choose == '1': unlock_user() # 選擇修改密碼 elif input_choose == '2': change_pwd() # 選擇退出界面 elif input_choose == '3': break else: print('You input error, try again!') print('-' * 30) continue
4、主程序購物商城
第一次運行,默認沒有賬號,需要注冊一個賬號(新賬號余額為)。
登錄成功后,要充值后,才可以購買商品。
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Version:Python3.5.0 import pickle def product_info(): ''' 商品信息,返回一個商品信息的字典 :return:product_list 和 product_list_index ''' # 初始化商品列表 product_dict = {'bike': 688, 'iphone6s': 5088, 'coffee': 35, 'car':88888, 'iPad Air': 3500, 'jacket': 300, 'MacBook pro': 12345, 'hamburger': 80} # 給商品添加索引 product_list_index = [(index+1, key, product_dict[key]) for index, key in enumerate(product_dict)] return product_dict,product_list_index def register(): ''' 注冊新用戶 :return: None ''' while True: # 輸入注冊賬號 username = input('Please input registered account: ').strip() # 輸入為空,重新輸入 if username == '':continue if username in user_dict: print('Account already exists, please input again!') continue else: pwd = input('Please input password: ') user_dict[username] = [pwd, 0, 0] print('Registered successfully!') # 把更新后的賬號字典保存到文件 user.pkl with open('user.pkl', 'wb') as f: pickle.dump(user_dict, f) break def login(): ''' 用戶登錄,驗證賬號密碼是否正確,密碼輸入3次則鎖定賬號 :return: None ''' flag = False # 初始化嘗試的次數 try_count = 0 while True: username = input('Please input the user: ').strip() # 輸入為空,重新輸入 if username == '': continue # 如果賬號存在 if username in user_dict: # 讀取用戶字典里面賬號輸錯次數,count為輸錯次數 count = user_dict[username][1] while True: if count < 3: pwd = input('Please input password: ') # 驗證密碼是否正確 if user_dict[username][0] == pwd: print('Login successfully!') # 進入二級菜單選項界面 flag = login_module(username) if flag: break else: # 密碼錯誤次數 count 加 1 count += 1 print('Password error! You have %s times,try again!' % (3-count)) continue else: # 輸錯3次后,賬號被鎖定 print('the %s is locked!' % username) # 把該賬號的錯誤次數更新到用戶字典中 user_dict[username][1] = 3 with open('user.pkl', 'wb') as f: # 重新寫入到文件user.pkl pickle.dump(user_dict, f) # 賬號被鎖定后,返回上級菜單 break else: try_count += 1 # 若果嘗試3次后,則返回上級菜單 if try_count == 3: break else: # 賬號不存在,則重新輸入,有3次機會 print('Account does not exist.you have %s times,try again!' %(3-try_count)) continue # 返回上級菜單 if flag: break def shopping(user): ''' 顯示商品信息,選擇商品索引號,即可加入購物車 :param user: 登錄賬號 :return: ''' # 調用商品信息函數,獲取商品信息字典以及索引 product, product_index = product_info() # 讀取user_dict字典,記錄登錄的賬號擁有的余額 money = user_dict[user][2] print('Your own %s YUAN'.center(35) % money) print('-' * 35) # 初始化一個空商品列表,記錄購買的商品 shopping_list = [] # 初始化購買商品總件數 total_number = 0 # 初始化花費金額 total_cost = 0 # 記錄商品最低價格 mix_price = min(product.values()) while True: for i in product_index: # 打印索引號,添加兩個空格顯示 print(i[0],end=' ') # 設置商品名稱長度13,左對齊顯示 print(i[1].ljust(13),end='') # 打印商品價格 print(i[2]) choose = input('Please choose the index of the product: ').strip() if choose.isdigit(): # 判斷輸入的索引是否正確,設置索引從1開始 if int(choose) in range(1, len(product_index)+1): # 記錄購買商品名稱,choose-1 為 該商品在product_index 列表中的索引 choose_product = product_index[int(choose)-1][1] # 判斷余額是否大於等於產品的價格 if money >= product[choose_product]: # 把商品加入購買清單 shopping_list.append(choose_product) # 計算花費的金額 total_cost += product[choose_product] # 余額可以購買最低價的商品 elif money >= mix_price: print('Your own %s YUAN, please choose other product.' % money) else: print('Your own money can not pay for any product,bye bye!') break else: print('Input the index error,try again!') continue # 標記退出 flag = False while True: print('Your rest money is %s.' % (money-total_cost)) continue_shopping = input('Continue shopping?y or n: ').strip() if continue_shopping == 'y': break elif continue_shopping == 'n': flag = True break else: continue if flag: break else: print('Input error,try again!') continue product_set = set(shopping_list) print('*' * 35) # 打印購物單表頭信息 print('Your shopping list'.center(35)) print('Product'.ljust(15),'Price'.ljust(7),'Number'.ljust(5),'cost'.ljust(7)) print('-' * 35) for i in product_set: number = shopping_list.count(i) total_number += number cost = product[i] * number print('%s %s %s %s' % (i.ljust(15),str(product[i]).ljust(7), str(number).ljust(5), str(cost).ljust(7))) print('-' * 35) print('''All number: %s All cost: %s''' % (str(total_number).ljust(7), str(total_cost).ljust(7))) print('Your rest money is %s.' % (money-total_cost)) with open('user.pkl','wb') as f: # 更新賬號的余額,保存到文件user.pkl user_dict[user][2] = money-total_cost pickle.dump(user_dict, f) def rechange(user): ''' 新注冊的賬號默認余額都是0元,登錄系統后需要進行充值才可以購買商品 :param user: 登錄賬號 :return: None ''' # 獲取參數user input_money = input('Please input the money of yourself: ').strip() while True: if input_money.isdigit(): user_dict[user][2] = int(input_money) with open('user.pkl','wb') as f: # 更新賬號的余額,保存到文件user.pkl pickle.dump(user_dict, f) print('Rechange successfully!') break else: print('Input error,try again!') continue def query_balance(user): ''' 查詢自己的余額 :param user: 登錄賬號 :return: None ''' # 打印余額 print('Your own money %s YUAN.'% user_dict[user][2]) def login_module(user): ''' 顯示登錄成功后的界面 :param user: 登錄賬號 :return: True ''' # 登錄后顯示界面的選項信息 second_menu = [['1', 'rechange'], ['2','query_balance'], ['3', 'shopping'], ['4', 'return'], ['5', 'exit']] while True: print('*' * 35) # 打印二級菜單選項 for i in second_menu: for j in i: print(j, end=' ') print('') choose = input('Please input the index: ').strip() if choose == '': continue # 選擇充值索引,執行充值函數 if choose == '1': rechange(user) # 選擇查詢余額索引,執行查詢余額函數 elif choose == '2': query_balance(user) # 選擇購物索引,執行購物函數 elif choose == '3': shopping(user) # 返回上級菜單 elif choose == '4': break # 結束程序 elif choose == '5': exit() # 輸入不匹配,重新輸入 else: print('Input error, try again!') continue return True if __name__ == '__main__': # 預讀取賬號信息文件 user.pkl,給函數調用 with open('user.pkl', 'rb') as f: # 讀取用戶信息 user_dict = pickle.load(f) # 構造主菜單列表選項 main_menu = [['1', 'register'], ['2','login'], ['3', 'exit']] while True: print('**** Welcome to mall ****') # 打印主菜單選項 for i in main_menu: for j in i: print(j, end=' ') print('') choose = input('Please input the index: ').strip() if choose == '': continue # 選擇注冊索引,執行注冊函數 if choose == '1': register() # 選擇登錄索引,執行登錄函數 elif choose == '2': login() # 選擇退出,則程序運行結束 elif choose == '3': print('Good bye!') break # 輸入不匹配,重新輸入 else: print('Input error, try again!') continue