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

如何实现多产品价格输入求和?sum函数报错问题解决

问题分析与解决方案

错误原因

sum()函数要求传入可迭代对象(比如列表、元组这类能遍历的集合),但你代码里的price是单个整数,直接传入sum(price)必然触发类型错误——整数不属于可迭代类型,无法被求和。

修正思路

先创建一个容器(比如列表)来存储每一次输入的价格,每次输入价格后将其添加到容器中,最后对整个容器调用sum()计算总价。同时修复原代码中无效输入的逻辑漏洞。

修正后的代码

# 初始化空列表存储所有产品价格
prices = []
while True:
    price = int(input("please enter the price for the product: $"))
    # 将当前价格加入列表
    prices.append(price)
    
    # 循环验证输入,直到用户输入有效选项
    while True:
        a = input("Do you want to enter another product? (Enter y for yes, n for no)")
        if a in ["y", "n"]:
            break
        print("Invalid input, please enter y or n")
    
    if a == "y":
        continue
    elif a == "n":
        total = sum(prices)
        print("The total amount for the products is: $", total)
        # 退出外层循环,结束程序
        break

关键改动说明

  • 新增prices = []:用来累计所有输入的产品价格
  • 每次输入价格后执行prices.append(price):把当前价格存入列表
  • 内层while循环处理输入验证:确保用户只能输入y或n,避免无效输入导致流程混乱
  • 输入n时调用sum(prices):对列表中的所有价格求和,最后退出循环结束程序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:25:24