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

Python不定参数求和程序报错求助:int与list无法执行加法运算

Fixing the TypeError in Your Sum Program

Let's walk through what's causing that error and how to fix it quickly.

The Root Cause

Your sum function uses *args, which is designed to accept multiple individual positional arguments and pack them into a tuple. But when you call sum(temp), you're passing a single list as the argument. That means inside the function, args becomes something like ([10, 20, 30],) — so when you loop through args, number is the entire list, not each integer. Trying to add an integer (tmp) to a list throws the TypeError you're seeing.

Solution 1: Unpack the List When Calling the Function

Use the * operator to unpack your list into individual arguments when calling sum. Also, don't forget to capture or print the return value of sum (right now you're just printing the original input list, not the total).

Here's the corrected code:

def sum(*args):
    tmp = 0
    for number in args:
        tmp = tmp + number
    return tmp

temp = [int(i) for i in input().split()]
total = sum(*temp)  # Unpack the list with * to pass each integer as a separate argument
print(total)  # Print the calculated sum instead of the input list

Solution 2: Modify the Function to Accept a List

If you prefer to pass a list directly instead of using *args, adjust the function to take a list parameter:

def sum(numbers):
    tmp = 0
    for number in numbers:
        tmp = tmp + number
    return tmp

temp = [int(i) for i in input().split()]
total = sum(temp)
print(total)

Bonus: Use Python's Built-in sum() Function

Just a heads-up — Python has a built-in sum() function that does exactly this task out of the box, so you could simplify your code even more:

temp = [int(i) for i in input().split()]
print(sum(temp))

This works because the built-in sum() accepts an iterable (like a list) directly, no need to write your own function for this basic use case.

内容的提问来源于stack exchange,提问作者Shabab Noor Islam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:19:11