0

I'm trying to make a program that adds the input, which will be in the form of '7 5 4 1' etc with a space between each number, and will add 7, 5, 4 and 1 for the output. So far I've got nothing working.

x = []
inp = int(input('Enter the expenses: '))
x.extend(inp.split())
print((sum)(x))

Any help would be appreciated

2 Answers 2

2

You'll need to convert the input to integers after splitting:

inp = input('Enter the expenses: ')
numbers = [int(i) for i in inp.split()]
print(sum(numbers))
Sign up to request clarification or add additional context in comments.

3 Comments

You might want to use raw_input and sum up numbers instead of inp :)
Getting the error: TypeError: unsupported operand type(s) for +: 'int' and 'str'
@Thibault: This is Python 3, there is no raw_input(). Fair point about the variable mix-up, corrected.
0
print(sum([int(x) for x in inp.split()]))

sum - sumarize int/float list [function(x) for x in list] - a python list comprehensions (a common and nice structure) int() - convert string to integer inp.split() - split a string into a list of strings

Explanation from inside to outside: you split the string into a list of strings, convert every string into integer-numbers and summarize it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.