user1688953
user1688953

Reputation: 11

python - please help cant figure out how to add up user input of an array

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

Answers (1)

Martijn Pieters
Martijn Pieters

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 to 0. The iterable‘s items are normally numbers, and the start 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

Related Questions