python购物车模块
生活随笔
收集整理的這篇文章主要介紹了
python购物车模块
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# 代碼實現: 購物車
# 功能要求: 1.用戶輸入總資產,例如:2000.
# 2.顯示商品列表,讓用戶根據序號選擇商品,加入購物車購買
# 3.如果商品總額大于總資產,提示賬戶余額不足,否則,購買成功
# 額外功能: 1.支持 一次購買多種商品多個數目
# 2.支持 多次購買
# 3.支持 在用戶繼續購買時顯示商品庫存
# 4.支持 在選擇商品時輸入任意字符,但必須是"商品編號:購買數量"的格式
# 5.支持 判斷初始資產是否可以買到最低單價的商品,以及購買后錢包余額是否可以繼續挑選商品,如不夠則提示用戶
# 6.支持 選擇的商品數量超出庫存時自動修改為最大庫存量,并提示用戶所選商品名和修改后的最大庫存數目
# 7.支持 購買后顯示用戶買了哪些商品,單價多少,數量多少,單種商品花費多少,總花費及余額
# 8.支持 選擇的商品總價大于資產數時,顯示需補充的差價
# 9.支持 商品售空時再次顯示時自動刪除該商品(不顯示該條目)
# 10.支持 判斷連續購買的次數并在用戶選擇結束購買時顯示"謝謝%d次惠顧
# 11.如需添加錄入新商品的功能,可用以下代碼實現:
# 12.還可添加一項: 將商品列表添加到本地json文件/服務器數據庫等 1 def format_insert_words_and_add_good_info(insert_words, separator_symbol): 2 insert_words_formatted_list = insert_words.split(separator_symbol) 3 # 此處省略類似下面select_goods()函數里的格式化輸入的步驟,自動刪除所有不合法的輸入 4 # 以下代碼默認good_insert的內容為合法內容,且省略了商品名已存在時修改錄入的商品名為'商品1'的步驟 5 good_temp_dic = {"name": insert_words_formatted_list[0], "price": int(insert_words_formatted_list[1]), 6 "allowance": int(insert_words_formatted_list[2])} 7 goods.append(good_temp_dic) 8 return goods 9 10 11 def show_insert(): 12 try: 13 good_insert = input("請輸入準備添加到貨架的商品的'名字','單價','數量',用英文逗號/英文句號或空格隔開: ").strip() 14 if ',' in good_insert: 15 format_insert_words_and_add_good_info(good_insert, ',') 16 elif '.' in good_insert: 17 format_insert_words_and_add_good_info(good_insert, '.') 18 elif ' ' in good_insert: 19 format_insert_words_and_add_good_info(good_insert, ' ') 20 else: 21 print('分隔符輸入不合法,未能錄入數據') 22 show_insert() 23 except KeyboardInterrupt: 24 print('\n手動終止錄入進程,再見...') 25 26 def write_goods_info(): 27 show_insert() 28 with open('goods_info.json','w') as info_file: 29 # 這里如果用遍歷goods的方法,只添加商品的字典,那么在上面'格式化插入的文字以及添加商品信息'方法里直接追加good_temp_dic 30 # with open('goods_info.json','a') as info_file: 31 info_file.write(goods) 32 錄入新商品&插入數據庫
# 功能要求: 1.用戶輸入總資產,例如:2000.
# 2.顯示商品列表,讓用戶根據序號選擇商品,加入購物車購買
# 3.如果商品總額大于總資產,提示賬戶余額不足,否則,購買成功
# 額外功能: 1.支持 一次購買多種商品多個數目
# 2.支持 多次購買
# 3.支持 在用戶繼續購買時顯示商品庫存
# 4.支持 在選擇商品時輸入任意字符,但必須是"商品編號:購買數量"的格式
# 5.支持 判斷初始資產是否可以買到最低單價的商品,以及購買后錢包余額是否可以繼續挑選商品,如不夠則提示用戶
# 6.支持 選擇的商品數量超出庫存時自動修改為最大庫存量,并提示用戶所選商品名和修改后的最大庫存數目
# 7.支持 購買后顯示用戶買了哪些商品,單價多少,數量多少,單種商品花費多少,總花費及余額
# 8.支持 選擇的商品總價大于資產數時,顯示需補充的差價
# 9.支持 商品售空時再次顯示時自動刪除該商品(不顯示該條目)
# 10.支持 判斷連續購買的次數并在用戶選擇結束購買時顯示"謝謝%d次惠顧
# 11.如需添加錄入新商品的功能,可用以下代碼實現:
# 12.還可添加一項: 將商品列表添加到本地json文件/服務器數據庫等 1 def format_insert_words_and_add_good_info(insert_words, separator_symbol): 2 insert_words_formatted_list = insert_words.split(separator_symbol) 3 # 此處省略類似下面select_goods()函數里的格式化輸入的步驟,自動刪除所有不合法的輸入 4 # 以下代碼默認good_insert的內容為合法內容,且省略了商品名已存在時修改錄入的商品名為'商品1'的步驟 5 good_temp_dic = {"name": insert_words_formatted_list[0], "price": int(insert_words_formatted_list[1]), 6 "allowance": int(insert_words_formatted_list[2])} 7 goods.append(good_temp_dic) 8 return goods 9 10 11 def show_insert(): 12 try: 13 good_insert = input("請輸入準備添加到貨架的商品的'名字','單價','數量',用英文逗號/英文句號或空格隔開: ").strip() 14 if ',' in good_insert: 15 format_insert_words_and_add_good_info(good_insert, ',') 16 elif '.' in good_insert: 17 format_insert_words_and_add_good_info(good_insert, '.') 18 elif ' ' in good_insert: 19 format_insert_words_and_add_good_info(good_insert, ' ') 20 else: 21 print('分隔符輸入不合法,未能錄入數據') 22 show_insert() 23 except KeyboardInterrupt: 24 print('\n手動終止錄入進程,再見...') 25 26 def write_goods_info(): 27 show_insert() 28 with open('goods_info.json','w') as info_file: 29 # 這里如果用遍歷goods的方法,只添加商品的字典,那么在上面'格式化插入的文字以及添加商品信息'方法里直接追加good_temp_dic 30 # with open('goods_info.json','a') as info_file: 31 info_file.write(goods) 32 錄入新商品&插入數據庫
額外功能實現代碼如下
1 goods = [{"name": "電腦", "price": 1999, "allowance": 100}, 2 {"name": "鼠標", "price": 10, "allowance": 100}, 3 {"name": "游艇", "price": 20, "allowance": 100}, 4 {"name": "美女", "price": 998, "allowance": 100}, 5 {"name": "帥哥", "price": 98, "allowance": 100}, ] 6 price_list = [] # 方便后面比較錢包余額是否大于最小單價 7 for good_index_temp in range(0, len(goods)): price_list.append(goods[good_index_temp]['price']) 8 9 10 def show_goods(): 11 print('**********商品列表**********') 12 print('編號\t\t商品\t\t價格\t\t庫存') 13 for good_index in range(0, len(goods)): 14 good_index += 1 15 print('{0}\t\t{1}\t\t{2}\t\t{3}'.format(good_index, goods[good_index - 1]['name'], 16 goods[good_index - 1]['price'], 17 goods[good_index - 1]['allowance'])) 18 19 20 def show_wallet(): 21 wallet = input('偷偷show一下錢包金額:').strip() 22 if wallet.isdigit(): 23 wallet = int(wallet) 24 if wallet < min(price_list): 25 print('窮逼滾,再給你一次機會') 26 show_wallet() 27 else: 28 print('總資產%d元,開始購物吧高富帥' % wallet) 29 return wallet 30 else: 31 print('糊弄誰呢?再給你一次機會') 32 show_wallet() 33 34 35 def select_goods(wallet, shopping_count=0): # return customer_choice_list, return selected_goods 36 customer_choice = input("請選擇商品編號及數量(以':'區分),使用空格隔開: ") 37 # ' 4:3:4 3:2 5:1 a:1 %:# # @ 1:120 2:m '' 38 customer_choice_list = customer_choice.split(' ') 39 print(customer_choice_list) 40 temp_list = customer_choice_list.copy() # 淺拷貝,以便后面遍歷時刪除無效項或非法項 41 for element in temp_list: 42 if element == '' or element == ' ': # 去空(無效項) 43 # print('過多的空格已被自動刪除') 44 customer_choice_list.remove(element) 45 elif ':' not in element: # 去掉無":"匹配的項(無效項) 46 # print('無效的匹配項已被自動刪除') 47 customer_choice_list.remove(element) 48 elif len(element.split(':')) != 2: # 去掉":"匹配后長度不為2(不是正常匹配)的項目(非法項) 49 # print('非法項已被自動刪除') 50 customer_choice_list.remove(element) 51 elif element.split(':')[0].isdigit() == 0 or element.split(':')[-1].isdigit() == 0: # 去掉首尾非數字的項(非法項) 52 # print('非商品編號或非正常商品數量,已自動刪除') 53 customer_choice_list.remove(element) 54 elif int(element.split(':')[0]) not in range(1, len(goods) + 1): # print('選擇的商品編號不存在,已自動刪除.') 55 customer_choice_list.remove(element) 56 elif int(element.split(':')[-1]) > goods[int(element.split(':')[0]) - 1]['allowance']: 57 customer_choice_list.remove(element) 58 element = element.split(':')[0] + ':' + str(goods[int(element.split(':')[0]) - 1]['allowance']) 59 print(">>>%s<<<選擇了過多的數量,已自動修改為最大庫存量>>%d<<" % ( 60 goods[int(element.split(':')[0]) - 1]['name'], goods[int(element.split(':')[0]) - 1]['allowance'])) 61 customer_choice_list.append(element) 62 del temp_list # 釋放臨時列表內存 63 print('您選擇了如下商品:????') # 只是展示給用戶知道他買了什么 64 selected_goods = [] # 只是展示給用戶知道他買了什么 65 for selection in customer_choice_list: 66 shopping_cart = {'商品名': goods[int(selection.split(':')[0]) - 1]['name'], 67 '單價': goods[int(selection.split(':')[0]) - 1]['price'], 68 '購買數量': int(selection.split(':')[-1])} 69 shopping_cart['所需金額'] = shopping_cart['單價'] * shopping_cart['購買數量'] 70 selected_goods.append(shopping_cart) 71 for selected_good in selected_goods: 72 print(selected_good) # 只是展示給用戶,并沒有他意 73 sum_price = 0 74 temp_list = goods.copy() # 淺拷貝商品列表,以便在刪除某商品時仍可計算客戶所花總價 75 for customer_choice_list_element in customer_choice_list: 76 goods[int(customer_choice_list_element.split(':')[0]) - 1]['allowance'] -= int( 77 customer_choice_list_element.split(':')[-1]) 78 if goods[int(customer_choice_list_element.split(':')[0]) - 1]['allowance'] == 0: 79 goods.pop(int(customer_choice_list_element.split(':')[0]) - 1) 80 sum_price += temp_list[int(customer_choice_list_element.split(':')[0]) - 1]['price'] * int( 81 customer_choice_list_element.split(':')[-1]) 82 wallet_allowance = wallet - sum_price 83 del temp_list # 釋放臨時內存 84 if wallet_allowance < 0: 85 print('余額不足,還需補充%d元.請下次多帶點錢來,窮逼!' % abs(wallet_allowance)) 86 elif wallet_allowance < min(price_list): 87 print('此次購物花費%d元,余額%d元' % (sum_price, wallet_allowance)) 88 print('余額暫不夠買任何商品了,下次請多帶點錢來吧!') 89 else: 90 print('此次購物花費%d元,余額%d元' % (sum_price, wallet_allowance)) 91 while 'Query_Go_On_Shopping?': 92 try: 93 customer_selection = input('是否需要繼續購買?Y/N').strip().lower() 94 if customer_selection == 'n': 95 shopping_count += 1 96 print('謝謝%d次惠顧,歡迎下次光臨...' % shopping_count) 97 break 98 elif customer_selection == 'y': 99 show_goods() # 展示商品余量 100 shopping_count += 1 101 select_goods(wallet_allowance, shopping_count) 102 break 103 else: 104 print('選擇無效,請重新選擇') 105 except KeyboardInterrupt: 106 print('手動打斷購物進程,再見') 107 108 109 if __name__ == '__main__': 110 show_goods() 111 select_goods(show_wallet()) 購物車模塊代碼不會實現的功能是:用戶在購買結束后不會詢問用戶是否繼續購買(因代碼里已實現多次購買功能)
代碼里用到的方法:
1??print()里的占位符,使用{0}{1}...方式占位
1 def show_goods(): 2 print('**********商品列表**********') 3 print('編號\t\t商品\t\t價格\t\t庫存') 4 for good_index in range(0, len(goods)): 5 good_index += 1 6 print('{0}\t\t{1}\t\t{2}\t\t{3}'.format(good_index, goods[good_index - 1]['name'], 7 goods[good_index - 1]['price'], 8 goods[good_index - 1]['allowance']))2??判斷用戶輸入的內容的數據類型(是否為數字)
1 def show_wallet(): 2 wallet = input('偷偷show一下錢包金額:').strip() 3 if wallet.isdigit(): 4 wallet = int(wallet) 5 if wallet < min(price_list): 6 print('窮逼滾,再給你一次機會') 7 show_wallet() 8 else: 9 print('總資產%d元,開始購物吧高富帥' % wallet) 10 return wallet 11 else: 12 print('糊弄誰呢?再給你一次機會') 13 show_wallet()3??去除列表里的元素時: 單純用while可能會刪不干凈
??用for遍歷則絕對會出錯,因為在遍歷列表(或字典)時不可修改其內容,不然其長度會改變,遍歷一定是不成功的
可以試試淺拷貝一份列表,for遍歷拷貝后的列表,在for循環里刪除原列表中想要刪除的元素,然后del淺拷貝的列表以釋放內存
1 # 接上文 2 # 因if判斷條件中變量命名寫得有點長,所以沒使用and連接,而是直接多個elif判斷 3 customer_choice = input("請選擇商品編號及數量(以':'區分),使用空格隔開: ") 4 # 如輸入內容為:' 4:3:4 3:2 5:1 a:1 %:# # @ 1:120 2:m '' 5 customer_choice_list = customer_choice.split(' ') 6 print(customer_choice_list) 7 temp_list = customer_choice_list.copy() # 淺拷貝,以便后面遍歷時刪除無效項或非法項 8 for element in temp_list: 9 if element == '' or element == ' ': # 去空(無效項) 10 # print('過多的空格已被自動刪除') 11 customer_choice_list.remove(element) 12 elif ':' not in element: # 去掉無":"匹配的項(無效項) 13 # print('無效的匹配項已被自動刪除') 14 customer_choice_list.remove(element) 15 elif len(element.split(':')) != 2: # 去掉":"匹配后長度不為2(不是正常匹配)的項目(非法項) 16 # print('非法項已被自動刪除') 17 customer_choice_list.remove(element) 18 elif element.split(':')[0].isdigit() == 0 or element.split(':')[-1].isdigit() == 0: # 去掉首尾非數字的項(非法項) 19 # print('非商品編號或非正常商品數量,已自動刪除') 20 customer_choice_list.remove(element) 21 elif int(element.split(':')[0]) not in range(1, len(goods) + 1): # print('選擇的商品編號不存在,已自動刪除.') 22 customer_choice_list.remove(element) 23 elif int(element.split(':')[-1]) > goods[int(element.split(':')[0]) - 1]['allowance']: 24 customer_choice_list.remove(element) 25 element = element.split(':')[0] + ':' + str(goods[int(element.split(':')[0]) - 1]['allowance']) 26 print(">>>%s<<<選擇了過多的數量,已自動修改為最大庫存量>>%d<<" % ( 27 goods[int(element.split(':')[0]) - 1]['name'], goods[int(element.split(':')[0]) - 1]['allowance'])) 28 customer_choice_list.append(element) 29 del temp_list # 釋放臨時列表內存然后就是for遍歷上述代碼返回的customer_choice_list,將與之對應的商品信息添加到購物列表里(這一步只是為了展示給用戶知道他買了什么東西)
注意: 如果需要讓用戶可以多次購物,那么他的多次購物的代碼一定要寫在一個函數里
?不然結算sum_price時就無法得到錢包余額,或需要重新調用結算函數,導致用戶還需要重新走一次購買流程
?
轉載于:https://www.cnblogs.com/aliter/p/8821639.html
總結
以上是生活随笔為你收集整理的python购物车模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指Offer面试题:4.从尾到头打印链
- 下一篇: set和map区别