You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python制作购物账单程序 新手入门实现求助

Python购物账单程序实现方案

你现有代码存在两个基础问题需要先修正:一是打印商品信息的print语句里字符串引号没有闭合,二是选购商品的逻辑不合理,无法支持用户购买多类商品、输入购买数量的需求。以下是可直接运行的完整实现:

完整代码

# 初始化商品价格字典,统一管理在售商品和对应单价
products = {
    "orange": 0.5,
    "apple": 1,
    "grape": 0.5,
    "banana": 0.5
}
# 存储用户购买记录、总数量、总金额
buy_records = {}
total_count = 0
total_amount = 0

customer = str(input("Customer's name: "))
print(f"Welcome to our store {customer}")
print("This is our products:")
# 遍历打印商品列表,避免硬编码
for name, price in products.items():
    print(f"{name.capitalize()} {price}$")

# 循环选购逻辑
while True:
    product_name = input("\nEnter the product you want to buy (enter 'quit' to end purchase): ").lower()
    if product_name == 'quit':
        break
    if product_name not in products:
        print("Sorry, we don't have this product")
        continue
    # 输入购买数量,做简单的输入合法性校验
    try:
        count = int(input(f"Enter the quantity of {product_name} you want to buy: "))
        if count <= 0:
            print("Quantity must be greater than 0")
            continue
    except ValueError:
        print("Please enter a valid number for quantity")
        continue
    # 写入购买记录
    if product_name in buy_records:
        buy_records[product_name] += count
    else:
        buy_records[product_name] = count
    # 累加总数量和总金额
    total_count += count
    total_amount += products[product_name] * count

# 打印账单,格式化对齐匹配你要的样式
print("\n" + " " * 10 + "BILL")
for name, count in buy_records.items():
    amount = products[name] * count
    # 左对齐保证样式整齐,宽度分别设为10、5
    print(f"{name.capitalize():<10} {count:<5} {amount}$")
print(f"{'Total:':<10} {total_count:<5} {total_amount}$")

功能说明

  • 支持用户选购多类商品,同个商品多次选购会自动累加数量
  • 自带输入合法性校验,避免用户输入不存在的商品、非数字数量等异常情况
  • 账单输出采用格式化对齐,和你给出的预期样式一致
  • 商品和单价统一存在字典里,后续要新增/修改商品只需要修改字典内容即可,不需要改动其他逻辑

内容的提问来源于stack exchange,提问作者MinhTris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:36:08