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

Python新手求助:实现无需修改代码的任意数量数字求和函数

解决任意数量数字求和的Python函数问题

Hey there! I see you're getting started with Python functions and want to expand your sum function to handle any number of inputs—great question! Let's break this down step by step.

问题分析

Your current sum function only accepts two parameters, which is why you have to modify it every time you want to add more numbers. Python has a handy feature called variable-length arguments (using *args) that lets you pass any number of positional arguments to a function.

改进后的求和函数

First, let's create a function that can take any number of numbers and sum them up. Also, we'll rename it to sum_numbers to avoid overwriting Python's built-in sum() function (that could cause unexpected issues later!):

def sum_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

# 测试一下
print(sum_numbers(5, 7))  # 输出12
print(sum_numbers(1, 2, 3, 4))  # 输出10
print(sum_numbers(10.5, 20.3, 5.2))  # 输出36.0

Or if you want to keep it super concise, you can use Python's built-in sum() directly inside your function:

def sum_numbers(*args):
    return sum(args)

结合用户输入的完整示例

Since you started writing a loop to ask for user input, let's put it all together into a working program that lets users enter as many numbers as they want, then calculates the total:

def sum_numbers(*args):
    return sum(args)

numbers_to_add = []
print("Enter numbers to sum, type 'done' when you're finished!")

while True:
    user_input = input("Enter a number: ")
    if user_input.lower() == 'done':
        break
    # 处理用户输入的非数字情况
    try:
        number = float(user_input)
        numbers_to_add.append(number)
    except ValueError:
        print("That's not a valid number—please try again.")

# 计算并输出结果
if numbers_to_add:
    total_sum = sum_numbers(*numbers_to_add)
    print(f"The total sum of your numbers is: {total_sum}")
else:
    print("You didn't enter any numbers to sum!")

关键点说明

  • *args acts like a tuple that collects all the positional arguments passed to the function—you can loop through it just like any other iterable.
  • Using try-except ensures your program doesn't crash if the user enters something that isn't a number.
  • We use *numbers_to_add when calling the function to "unpack" the list of numbers into individual arguments for sum_numbers.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:42:59