一道簡單的python面試題-購物車

要求實現:
1.程序開始運行時要求手動填入工資金額
2.而後展現一份帶有價格的商品列表
3.選擇某個商品,足夠金額購買就添加到購物車,不然提示沒法購買
4.退出後列出購物車清單python

 

#!/usr/bin/python
#
-*- coding:utf-8 -*- # Author: Jacket #定義商品列表 product_list = [ ('macair',8000), ('iphone',3000), ('xiaomi',1000), ('mobike',800), ('coffee',50), ] #購物車默認爲空 shopping_list = [] salary = input("input your salary:") if salary.isdigit(): #判斷輸入的工資金額是否爲數字 salary = int(salary) #轉化爲整型數據 while True: for index,item in enumerate(product_list): print(index,item) #展現商品列表 user_choice = input("你要買啥:") if user_choice.isdigit(): user_choice = int(user_choice) if user_choice < len(product_list) and user_choice >= 0: #判斷用戶輸入的id是否在商品列表長度範圍內 p_item = product_list[user_choice] #將用戶輸入的id做爲商品列表的索引,定位用戶選擇的商品信息 if p_item[1] <= salary: #商品價格小於或等於餘額 shopping_list.append(p_item) #添加此商品到購物車 salary -= p_item[1] #剩餘工資 = 減去商品價格後的餘額 #print("你購買的商品是%s,剩餘的餘額是%s" % (shopping_list,salary)) print("add %s to your shopping cart succee,and your salary is %s" % (p_item[0],salary)) else: print("你的餘額%s不足,沒法購買商品" %salary) else: print("你選擇的商品不存在") elif user_choice == 'q': print("-------購物車清單-------") for i in shopping_list: print(i) exit() else: print("格式不正確,請輸入數字或者q...") else: print("你輸入的餘額[%s]格式不正確" % salary)
相關文章
相關標籤/搜索