简易购物车用于了解购物车的大致原理,利用Python实现简易购物车的基本功能,即:用户将所选择的商品放入购物车中,结算时自动输出所购买商品及所剩余额。
# -*- coding: UTF-8 -*- product_list = [ (‘iphone‘,6000), (‘Mac Pro‘,10000), (‘bike‘,2000), (‘Watch‘,16000), (‘coffee‘,30), (‘book‘,40)]shopping_list = []salary = input("Input your salary:")if salary.isdigit(): #isdigit判断是否是一个整数数字,若是则会返回一个真(Ture) salary = int(salary) while True: ‘‘‘for item in product_list: print(product_list.index(item),item) 这样写也是可以的,获取下标作为产品的产品编号 ‘‘‘ for index,item in enumerate(product_list): print(index,item) #打印商品列表 user_choice = input("what choice your buying?") 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 = salary - p_item[1] print("Added %s into shopping cart,Your current balance is %s" %(p_item,salary)) else: print("余额不足") 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") 简易购物车仅能实现静态的商品列表。
时间: 2024-10-06 00:16:29