You say you need to use a single input. In this case we can split our input using the .split(separator)
method of the string, which returns a list of parts of the given string. separator
argument is optional: if the user enters the numbers separated by whitespace characters, you don't need to pass this argument, otherwise you need to pass a 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")
Note: I'll suppose your numbers are separated by a whitespace character in the next part of answer.
If we would like to print the numbers
list, we will get this output:
>>> numbers = input("Enter the numbers... ").split()
Enter the numbers... 1 2 3 4
>>> print(numbers)
['1', '2', '3', '4']
As we can see all the items of our list are strings (because of the quotation marks: '1'
, not 1
). If we'll try to concatenate them together we'll get something like this: '1234'
. But if you want to concatenate them together as numbers, not strings, we'll need to convert them to int (for integers) or float (for non-integer numbers) type. If we have one number, it can be done easily: int(number)
. But we have got a list of numbers and we need to convert every element to int
.
We can use the map(func, iterable)
function. It will apply the func
to every item of iterable
and return a map
object - an iterator (NOT a list!):
numbers = map(int, numbers)
Note: if we would like to represent it as a list, we can simply do:
numbers = list(map(int, numbers))
though it is not necessary here.
And now we can throw all the numbers to your add_number(*args)
function using the asterisk (*) - pack them:
add_number(*numbers)
Note: you can also use sum
function to add all the numbers from iterable - in this case, you don't need to pack the args, because it gets a single iterable of numbers:
sum_ = sum(numbers)
And then let's print
our result:
print(sum_)
Important Note: sum(iterable)
returns the sum of the numbers and prints nothing, while your add_number(*args)
function returns None and prints the number (it is not the same thing!). Here is a good, detailed explanation.
Here is the whole code what we've written:
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)
And here is a one-liner that does the same thing - it uses sum
function instead of the add_number
and hence doesn't require anything else in the code:
print(sum(map(int, input("Enter the numbers... ").split())))