#!/usr/bin/env.python # -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: shopping Description : Author : lym date: 2018/2/24 ------------------------------------------------- Change Activity: 2018/2/24: ------------------------------------------------- """ __author__ = 'lym' # 定義一個商品列表,裏面寫入商品的值和價格 product_list = [ ('iphone', 5000), ('coffee', 31), ('bicyle', 888), ('iwatch', 2666), ('Mac Pro', 12000), ('book', 88) ] shopping_list = [] # 空列表,存放購買的商品 salary = input("請輸入你的工資:") if salary.isdigit(): # isdigit() 方法檢測字符串是否只由數字組成,是則返回True,不然返回False salary = int(salary) while True: for index, i in enumerate(product_list): # index做爲下標索引 print(index, i) # enumerate() 函數用於將一個可遍歷的數據對象(如列表、元組或字符串)組合爲一個索引序列,同時列出數據和數據下標,通常用在 for 循環當中。 user_choice = input("請輸入你要購買的商品:") if user_choice.isdigit(): user_choice = int(user_choice) if user_choice < len(product_list) and user_choice >= 0: product_choice = product_list[user_choice] if product_choice[1] < salary: # 買得起 shopping_list.append(product_choice) # 買得起,就放入購物車 salary -= product_choice[1] print( "Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m" % (product_choice, salary)) else: print("\033[41;1m你的餘額只剩%s啦,還買個叼啊!\033[0m" % salary) print("---------shopping list-----------") for s_index, s in enumerate(shopping_list): print(s_index, s) print("---------shopping list-----------") print("你的餘額爲:\033[31;1m%s\033[0m" % salary) else: print("沒有這個商品") elif user_choice == "q": print("---------shopping list-----------") for s_index, s in enumerate(shopping_list): print(s_index, s) print("---------shopping list-----------") print("你的餘額爲:\033[31;1m%s\033[0m" % salary) exit() else: print("輸入錯誤") else: print("輸入錯誤")