How can I write a definition for a function that is passed a list of numbers and returns the sum of the numbers in that list using a while loop?

I'm trying this, but it's not working

def sumList():
num = [1,2,3]
sum = 0
while num != str:
for i in num:
sum += i
print(sum)

Is there a way to not even use for?

Recommended Answers

All 2 Replies

You have made a function that dont get passed(and argument) and it dont return anything as your description say.

First the easy way with a build in(sum)

def sum_lst(my_list):
    return sum(my_list)

num = [1,2,3]  
print sum_lst(num)  #6

Here function is passes a list(num) and return the sum.
And i think this is homework,so you may have to use a while loop.

def sum_elements(my_list):
    total = 0
    index = 0
    while index < len(my_list):
        total += my_list[index]
        index += 1
    return total
 
num = [1,2,3]
print sum_elements(num)  #6

Next time use code tag and look more at how argument and return in a function works.

Ah, I see thank you. Sorry about not putting it in the code tags. I can't find the edit post button either.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.