需求 要求用戶輸入總資產,例如:2000 顯示商品列表,讓用戶根據序號選擇商品,加入購物車 購買,若是商品總額大於總資產,提示帳戶餘額不足,不然,購買成功。 附加:可充值、某商品移除購物車
測試信息 goods = [ {"name": "電腦", "price": 1999}, {"name": "鼠標", "price": 10}, {"name": "遊艇", "price": 20}, {"name": "美女", "price": 998}, ]
goods = [ {"name": "電腦", "price": 1999}, {"name": "鼠標", "price": 10}, {"name": "遊艇", "price": 20}, {"name": "美女", "price": 998}, ] # 定義函數,格式化菜單輸出 def menu(): count=0 for i in goods: print('【{0}】 {1} {2}'.format(count,i['name'],i['price'])) count+=1 # 定義購物車空列表 goods_list=[] tag=True while tag: money=input('How much are you ?').strip() # 判斷輸入的數據類型 if money.isdigit() and len(money) != 0 : money = int(money) while tag: menu() choice=input('請輸入你要購買的商品序號:').strip() if choice.isdigit() and len(choice) != 0 : choice=int(choice) if choice >= 0 and choice <= 3: # 取出所買商品的信息 g_l=[] for i in goods: g_l.append({i['name']: i['price']}) info=g_l[choice] price_list=list(info.values()) price=int(price_list[0]) name_list=list(info.keys()) # 使用a的值來控制下面兩層while循環 a=1 while a == 1: if money >= price: money=money - price print('商品已加入購物車,當前餘額爲{}'.format(money)) goods_list.append(name_list[0]) while a == 1: print('當前購物車裏商品:',goods_list) choices=input(''' 【E】 結帳 【D】 刪除商品 【S】 繼續購買 請選擇:''').strip().lower() if choices != 'e' and choices != 'd' and choices != 's': print('選擇錯誤,請從新輸入:') continue if choices == 's': a=0 break if choices == 'e': print('已結帳,當前餘額爲{}'.format(money)) a=0 tag=False if choices == 'd': print(goods_list) delet=input('請輸入你想刪除的商品:').strip() if delet in goods_list: goods_list.remove(delet) print('%s 刪除成功!' %delet) continue else: print('此商品不在購物車') continue else: print('你買不起這個,請選擇:') choicess=input(''' 【A】 從新選擇商品 【B】 充值 【C】 退出 請選擇:''').strip().lower() if choicess == 'a': a=0 if choicess == 'c': exit() while a == 1: if choicess == 'b': recharge=input('請輸入充值金額:').strip() if recharge.isdigit() and len(recharge) != 0: recharge = int(recharge) money = money + recharge print('充值成功,當前金額爲:',money) break else: print('充值金額有誤') continue else: print('沒有此商品,請從新選擇') continue else: print('你的輸入有誤,請輸入數字:') continue