Python 练习1——简易购物车
简易购物车用于了解购物车的大致原理,利用Python实现简易购物车的基本功能,即:用户将所选择的商品放入购物车中,结算时自动输出所购买商品及所剩余额。
1 # -*- coding: UTF-8 -*- 2 product_list = [ 3 ('iphone',6000), 4 ('Mac Pro',10000), 5 ('bike',2000), 6 ('Watch',16000), 7 ('coffee',30), 8 ('book',40) 9 ] 10 shopping_list = [] 11 salary = input("Input your salary:") 12 if salary.isdigit(): #isdigit判断是否是一个整数数字,若是则会返回一个真(True) 13 salary = int(salary) 14 while True: 15 '''for item in product_list: 16 print(product_list.index(item),item) 这样写也是可以的,获取下标作为产品的产品编号 17 ''' 18 for index,item in enumerate(product_list): 19 print(index,item) #打印商品列表 20 user_choice = input("what choice your buying?") 21 if user_choice.isdigit(): #选择数字类型 22 user_choice = int(user_choice) 23 if user_choice < len(product_list) and user_choice >= 0: 24 p_item = product_list[user_choice] #通过下标取商品 25 if p_item[1] <= salary: #商品价格小于用户余额,即能买得起 26 shopping_list.append(p_item) 27 salary = salary - p_item[1] 28 print("Added %s into shopping cart,Your current balance is %s" %(p_item,salary)) 29 else: 30 print("余额不足") 31 else: 32 print("product code [%s] is not exist!" % (user_choice)) 33 34 elif user_choice == 'q': 35 print('---------shopping list--------- 36 ') 37 for p in shopping_list: 38 print(p) 39 print("Your current balance:",salary) 40 exit() 41 else: 42 print("invalid option")
简易购物车仅能实现静态的商品列表。
浙公网安备 33010602011771号