Reputation: 11
how do I Write using python a function, sum(a), that takes an array, a, of numbers and returns their sum?
I tried this but i am unable to figure out how get the user input of the array of number this is what i have so far
Upvotes: 0
Views: 262
Reputation: 1125058
You take the built-in function sum()
:
>>> sum(range(10))
45
From the documentation:
Sums
start
and the items of an iterable from left to right and returns the total.start
defaults to0
. The iterable‘s items are normally numbers, and thestart
value is not allowed to be a string.
If the user input is in the form of strings, you need to turn those into integers first. A generator expression could do that for you:
>>> user_input = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> sum(int(v) for v in user_input)
45
Upvotes: 3