0

i need to input values split the space

output should return me sum of this values

so if i putting 1 4

my code should return 5

a,b = input().split(" ")
print (int(a)+int(b))

this code is working

but i need to define variables!

how i can input 5 value? 10 values? and don't define this variables somewhere

for example i want input 1 1 1 1 1

and get 5

2
  • 1
    Can the numbers be floating point? What if the user inputs something other than numbers? Commented Apr 21, 2020 at 13:15
  • this example just for ints Commented Apr 21, 2020 at 13:17

3 Answers 3

3
# input '1 1 1 1 1'
list_of_values = input().split(" ")
# list_of_values = ['1', '1', '1', '1', '1']
print(sum(int(a) for a in list_of_values))
# sum of [1, 1, 1, 1, 1] is 5
Sign up to request clarification or add additional context in comments.

Comments

1

One liner pythonic way:

print('Sum is : ' + str(sum(list(map(int, input("Enter Numbers: ").split())))))

Comments

0

You could do something like this:

vars = input(">")
vars = vars.split()
sum = 0

#calculate sum
for number in vars:
    try:
        int(number)
        sum += int(number)
    except:
        pass

#prettify
tempVars = vars
vars = []
for number in tempVars:
    try:
        int(number)
        vars.append(number)
    except:
        pass

print(f"Sum of {vars}: {sum}")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.