0

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

2
  • 3
    You seem to be missing some code in your question. If you have trouble formatting it, see How do I format my code blocks? Commented Sep 21, 2012 at 13:50
  • 2
    This smells like homework. Please post your work so far as Martijn has requested. Commented Sep 21, 2012 at 14:38

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

For the user input part (the bit it seems like the OP is having a problem with) you can use input() (or raw_input() in py3k).

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.