1. 程式人生 > >cart_購物車小程序

cart_購物車小程序

inpu ren blog put 必須 color leon ppi watch

 1 #author:leon
 2 product_list= [
 3     (iphone,5800),
 4     (mac pro,9800),
 5     (bike,800),
 6     (watch,6000),
 7     (coffee,31),
 8     (book,120)
 9 ]
10 shopping_list= []
11 salary = input("input  your  salary:")
12 if  salary.isdigit():
13     salary=int(salary)
14     while  True:
15
for item in product_list: 16 print(product_list.index(item),item) #循環打印產品編號和產品列表(產品名加產品價格) 17 user_choice = input("選擇買什麽>>>>:") 18 if user_choice.isdigit(): #如果是數字成立, 19 user_choice=int(user_choice) #把數字轉換成整型int
20 if user_choice<len(product_list) and user_choice>=0: #輸入的數字長度必須小於產品列表的長度,#len()取列表長度 21 P_item=product_list[user_choice] #找出數字user_choice代表的值。例:name[1]找出產品 22 if P_item[1] <= salary: #買得起。列表product_list中嵌套了P_item元組。所以P_item[1],表示取出元祖中第二個值,即價格。
23 shopping_list.append(P_item) 24 salary -=P_item[1] 25 print("add %s into your shopping cart ,you current balance is \033[31;1m%s \033[0m"%(P_item,salary)) 26 else: 27 print("\033[32;1m 你的余額不足 %s"%salary) 28 29 30 elif user_choice =="q": 31 print(".....shopping list ...") 32 for p in shopping_list: #循環打印列表 33 print(p) 34 print("your balance %s " %salary) 35 exit() 36 37 38

cart_購物車小程序