需求:
1.啟動程序后,讓用戶輸入工資,然后打印商品列表
2.允許用戶根據商品編號購買商品
3.用戶選擇商品后,檢測余額時候夠,夠就直接扣款,不夠就提醒
4.可隨時退出,退出時,打印已購買商品和余額
python環境:3.6.5
知識點:if-else,for,while
代碼:
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Author:coding2018 ''' 需求: 1.啟動程序后,讓用戶輸入工資,然后打印商品列表 2.允許用戶根據商品編號購買商品 3.用戶選擇商品后,檢測余額時候夠,夠就直接扣款,不夠就提醒 3.可隨時退出,退出時,打印已購買商品和余額 ''' #商品列表 product_list = [ ('iPhone',5800), ('Mac Pro',9800), ('Bike',800), ('Watch',10600), ('Coffee',31), ('Ales Python',120) ] #購物車 shopping_list = [] #輸入工資 salary = input("Input your salary:") #isdigit() 方法檢測字符串是否只由數字組成。 if salary.isdigit(): #salary轉換成int型 salary = int(salary) #循環 while True: #取product_list中商品下標和商品 #enumerate() 函數用於將一個可遍歷的數據對象(如列表、元組或字符串) # 組合為一個索引序列,同時列出數據和數據下標,一般用在 for 循環當中 for index,item in enumerate(product_list): print(index,item) print("q 退出") # for item in product_list: # print(product_list.index(item),item) #輸入表購買商品的標號 user_choice = input("選擇要買的商品編號>>>:") if user_choice.isdigit(): user_choice = int(user_choice) #判斷輸入編號 if user_choice < len(product_list) and user_choice >= 0: p_item = product_list[user_choice] #判斷商品價格是否小於余額 if p_item[1] <= salary: #買的起 #商品加入購物車 shopping_list.append(p_item) #余額減少 salary -= p_item[1] print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m" %(p_item,salary)) else: print("\033[41;1m你的余額只有[%s],無法購買\033[0m" % salary) else: print("product code [%s] is not exist!" % user_choice) elif user_choice == 'q': print('--------------shopping list---------------') for p in shopping_list: print(p) print("Your current balance:",salary) exit() else: print("invalid option") else: print("該輸入不是只由數字組成")