user3879060
user3879060

Reputation: 25

Python - addition

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

Upvotes: 0

Views: 138

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121644

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))

Upvotes: 2

Kuishi
Kuishi

Reputation: 157

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.

Upvotes: 0

Related Questions