您说您需要使用单个输入。在这种情况下,我们可以使用字符串的.split(separator) 方法拆分输入,该方法返回给定字符串的部分列表。 separator 参数是可选的:如果用户输入的是空格字符分隔的数字,则不需要传递此参数,否则需要传递分隔符。
numbers = input("Enter the numbers... ").split() # if numbers are separated by any of whitespace characters ("1 2 3 4")
numbers = input("Enter the numbers... ").split(", ") # if numbers are separated by a comma and a space ("1, 2, 3, 4")
注意:我假设您的数字在答案的下一部分用空格字符分隔。
如果我们想打印numbers 列表,我们会得到这个输出:
>>> numbers = input("Enter the numbers... ").split()
Enter the numbers... 1 2 3 4
>>> print(numbers)
['1', '2', '3', '4']
我们可以看到列表中的所有项目都是字符串(因为引号:'1',而不是1)。如果我们尝试将它们连接在一起,我们将得到如下结果:'1234'。但是,如果您想将它们作为数字而不是字符串连接在一起,我们需要将它们转换为 int(对于整数)或 float(对于非整数)类型。如果我们有一个号码,就可以轻松完成:int(number)。但是我们有数字列表,我们需要将每个元素转换为int。
我们可以使用map(func, iterable) 函数。它将func 应用于iterable 的每个项目并返回一个map 对象 - 一个迭代器(不是列表!):
numbers = map(int, numbers)
注意:如果我们想将它表示为一个列表,我们可以简单地这样做:
numbers = list(map(int, numbers))
虽然这里没有必要。
现在我们可以使用星号 (*) - pack 将所有数字扔给您的 add_number(*args) 函数:
add_number(*numbers)
注意:您还可以使用sum 函数将所有可迭代的数字相加 - 在这种情况下,您不需要打包 args,因为它会得到一个可迭代的数字:
sum_ = sum(numbers)
然后让我们print我们的结果:
print(sum_)
重要提示: sum(iterable) 返回数字的总和并且不打印任何内容,而您的 add_number(*args) 函数返回 None 并打印数字(这不是一回事!)。 Here 是一个很好的详细解释。
这是我们编写的全部代码:
def add_number(*args):
total = 0
for number in args:
total += number
print(total)
numbers = input("Enter the numbers... ").split() # if numbers are separated by any of whitespace characters ("1 2 3 4")
numbers = map(int, numbers)
add_number(*numbers)
这是一个做同样事情的单行代码 - 它使用 sum 函数而不是 add_number,因此不需要代码中的任何其他内容:
print(sum(map(int, input("Enter the numbers... ").split())))