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

Is there a way to not even use for?

8 Years
Discussion Span
Last Post by JuvenileMango

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.

Edited by snippsat: n/a


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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.