Your code is working, but not for the specific input the practice center is giving. Make this modification:
nums = [int(x) for x in input("Enter numbers: ").split()]
print("The sum of a and b is", sum(nums))
By the way, sum
is a built-in function, so you don't have to write it yourself. The only line that really changed is this:
nums = [int(x) for x in input("Enter numbers: ").split()]
nums
will be a list of numbers, as the name implies. The next part is the list comprehension. input("Enter numbers: ").split()
will take the input and split it on any whitespace. For instance, 'hello world'
will be turned into a list with ['hello', 'world']
. In this case, '1 1'
will be turned into a list with ['1', '1']
. Then, with the list comprehension, you are turning each element into an integer (['1', '1']
-> [1, 1]
). Then, you pass this list into sum
. Also, this does the same thing as the list comprehension:
nums = list(map(int, input("Enter numbers: ").split()))
It doesn't matter which one you choose. If you wanted to get real fancy, you can do the whole thing in one line:
print("The sum of a and b is", sum(map(int, input("Enter numbers: ").split())))