1. 程式人生 > 其它 >python---最基本的購物車程式

python---最基本的購物車程式

程式:購物車程式

需求:

  1. 啟動程式後,讓使用者輸入工資,然後列印商品列表
  2. 允許使用者根據商品編號購買商品
  3. 使用者選擇商品後,檢測餘額是否夠,夠就直接扣款,不夠就提醒 
  4. 可隨時退出,退出時,列印已購買商品和餘額
 1 product = [
 2     ("ipad", 500),
 3     ("touch", 1000),
 4     ("watch", 2000),
 5     ("iphone", 3000),
 6     ("macair", 4000),
 7     ("macpro", 5000)
 8 ]
 9 
10 shopping_list = []
11 money = input("請輸入你手中的資金:
") 12 if money.isdigit(): # 判斷輸入的是不是數字 13 money = int(money) # 將輸入的轉換成int型別 14 while True: # 進入迴圈 15 # for item in product: 16 # print(item) 17 # print(product.index(item), item) # 通過index列印下標 18 for index, item in enumerate(product): # 列印商品列表&取出下標
19 print(index, item) 20 user_choice = input("請選擇商品編號>>>:") # 輸入需要購買的商品編號(列表下標) 21 if user_choice.isdigit(): # 判斷輸入的是否為數字型別 22 user_choice = int(user_choice) # 將輸入的轉換成int型別 23 if user_choice< len(product) and user_choice>= 0: #
判斷輸入的編號是否存在列表中 24 # p_item為元組 25 p_item = product[user_choice] # 通過輸入的商品編號(下標),取出商品(加入購物車) 26 print(p_item) 27 if p_item[1] <= money: # 買得起 28 shopping_list.append(p_item) # 加入購物車 29 money -= p_item[1] # 扣錢 30 # 列印已購買的商品和餘額 31 print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m" % (p_item, money)) 32 else: 33 print(" \033[31;1m 你的餘額只剩[%s]啦,還買個毛線 \033[0m " % money) # 列印餘額不足 34 else: 35 print("product code [%s] is not exist" %user_choice) # 輸入的商品編號不存在 36 elif user_choice == "q": # 退出 37 print("-----------shopping list------------") 38 for p in shopping_list: # 迴圈列印已購買的商品 39 print(p) 40 print("Your current banlance:", money) 41 exit() 42 else: 43 print("invalid option") 44 break