Python新手求助:如何高效实现商店订单自动计算总价(支持多商品)
商店程序总价计算优化方案
问题描述
刚学习Python两天,编写了一个简易的商店程序,用户下单后程序会告知总价。目前通过if语句实现了单商品及特定组合的总价展示,但该方法效率低下,且无法自动计算任意多种商品组合的总价,附上原始代码:
print("Welcome to the Apple Store!") name = input("What is your name?\n") print("Hello " + name + ", welcome to the Apple store!\n\n") products = "iPhone 14 $10,000, Macbook Air $14,000, iPhone 13 $8,000\n" value = input iPhone_14 = 10000 Macbook_Air = 14000 iPhone_13 = 8000 a = iPhone_14 + Macbook_Air order = input("Here is our list of products, what would you want?\n" + products) if order == "iPhone 14": print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(iPhone_14)) if order == "Macbook Air": print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(Macbook_Air)) if order == "iPhone 13": print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(iPhone_13)) if order == "iPhone 14, Macbook Air": print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(a))
优化思路与解决方案
- 用字典存储商品信息:将商品名称和对应价格存入字典,实现快速查找,后续新增商品只需修改字典,无需添加大量判断语句。
- 标准化输入处理:将用户输入的订单按逗号拆分,去除每个商品名称前后的空格,确保能匹配字典中的键。
- 自动计算总价:遍历拆分后的商品列表,累加对应价格,同时区分有效和无效商品,提升程序健壮性。
优化后的完整代码
print("Welcome to the Apple Store!") name = input("What is your name?\n") print(f"Hello {name}, welcome to the Apple store!\n\n") # 字典存储商品与价格,便于扩展和查询 product_prices = { "iPhone 14": 10000, "Macbook Air": 14000, "iPhone 13": 8000 } # 自动生成商品列表字符串,避免手动拼接 products = ", ".join([f"{item} ${price:,}" for item, price in product_prices.items()]) + "\n" order_input = input(f"Here is our list of products, what would you want?\n{products}") # 拆分输入并清理空格,得到商品列表 ordered_items = [item.strip() for item in order_input.split(",")] total = 0 valid_items = [] invalid_items = [] # 遍历订单计算总价,区分有效/无效商品 for item in ordered_items: if item in product_prices: total += product_prices[item] valid_items.append(item) else: invalid_items.append(item) # 输出结果 if valid_items: items_str = ", ".join(valid_items) print(f"Alright {name}, your {items_str} will be prepared.\n\nThe total amount will be ${total:,}") if invalid_items: invalid_str = ", ".join(invalid_items) print(f"Note: {invalid_str} are not available in our store.")
优化点说明
- 扩展性强:新增商品只需在
product_prices字典中添加键值对,无需修改核心逻辑。 - 支持任意组合:无论用户输入多少种商品组合,都能自动计算总价。
- 错误提示:识别无效商品并告知用户,提升用户体验。
- 格式优化:用f-string简化字符串拼接,价格带千位分隔符更直观。
内容的提问来源于stack exchange,提问作者eden
相关产品推荐
相关产品推荐

