I'm trying to design a function that accepts a list of numbers as an argument. I can get the program working when i put a list into the programme but I can't figure out how to allow a user to enter a series. What i've got so far is below. Any help would be appreciated.

def main():

    list= [2, 4, 6, 8, 9, 12, 6, 10, 9, 6, 7 ]   

    my_sum = sum(list)

    # Display the sum
    print "The sum of numbers in the list is", my_sum

def sum(list):
    if list == []:
        return 0
     else:
        return list [0] + sum (list[1:])


main()

Edited 4 Years Ago by SpartanIE

Your sum is correct, just do not use sum as function name. You just need to make user input function, look code snippets section for examples.

Avoid using names like list and sum since they are internal to Python. Something like this will work:

mylist = []
prompt = "%d) enter an integer (-99 to stop): "
for k in range(1000):
    x = int(raw_input(prompt % (k+1)))
    if x == -99:
        break
    mylist.append(x)

print(mylist)  # test

'''
1) enter an integer (-99 to stop): 4
2) enter an integer (-99 to stop): 66
3) enter an integer (-99 to stop): 7
4) enter an integer (-99 to stop): 12
5) enter an integer (-99 to stop): -99
[4, 66, 7, 12]

'''

Edited 4 Years Ago by bumsfeld

For fun here is recursive function producing sum of numbers without remembering the numbers:

def my_sum():
    n = raw_input('Next number or empty to finish: ')
    return (float(n) + my_sum()) if n else 0

s = my_sum()
print "The sum of numbers is", s

Report any not working code sections by reporting them by Flag Bad Post link.

Do not select code snippet from type of article but type for example to search box input snippet and to Forum Python. The limiting from menu to Code Snippet does not work same time with Forum selected.

Edited 4 Years Ago by pyTony

Comments
clever
This article has been dead for over six months. Start a new discussion instead.