購物車小程序(while循環,列表)

 1 while True:
 2     salary = input("please input your salary:")
 3     if salary.isdigit():
 4         salary=int (salary)
 5         break
 6     else:
 7         print("Invalid input! please input a number:")
 8 
 9 product_cart = [['iphone6s',5800],                 #定義商品列表
10                 ['macbook',9000],
11                 ['coffee',30],
12                 ['python book',80],
13                 ['bicycle',1500]
14                 ]
15 shopping_cart = []                                 #定義購物車
16 balance=salary
17 
18 while True:
19     for i,v in  enumerate(product_cart,1):         #enumerate參數將商品列表循環打印,而且第一行從1開始 加上序號
20         print(i,v)
21 
22     choise = input("please input your selection[typing 'q' to quit]:")
23     if choise.isdigit():                           #判斷是不是數字
24         choise=int(choise)
25         if choise >=1 and choise<=len(product_cart): #判斷輸入的字符是否符合商品列表所在的範圍
26             sales =product_cart[choise-1]            #將用戶選擇的商品賦值給sales
27             if balance >=sales[1]:                   #判斷餘額是否足夠購買該商品
28                 balance -=sales[1]                   #購買完後將餘額減去商品價格
29                 shopping_cart.append(sales)          #將商品加入購物車
30                 print("your balance is %s :"%balance)
31                 print()
32             else:
33                 print("your balance is %s,not enough to buy this one,please try another products!"%balance,)
34                 print()
35 
36 
37         else:
38             print("no such a selection")
39     elif choise == 'q':                            #判斷是不是q選擇退出
40         print("your shopping cart is:")
41         for i, v in enumerate(shopping_cart, 1):   
42             print(i, v)
43         break
44     else:
45         print("Invalid typing.please typing a number!") #非數字執行的操做
View Code
相關文章
相關標籤/搜索