Digit sum



Hi all. Don't really understand why this isn't working.

From what I understand, the code in line 5 is supposed to add the incremental of 'num' within the parameter from index 0 to end of the parameter. (in this example, from index 0 to index 2)

Am I making a mistake somewhere?
thanks in advanced!

def digit_sum(x):   
    x = str(x)
    for num in range(0,len(x)-1):
        ans = 0 
        ans += int(num)
    return ans


placing answer = 0 inside the loop means each run/iteration of the loop, ans gets assigned a value of zero, which means ans not accumulating the total (because it resets to zero each run of the loop, not maintaining the value which is already there)

place ans = 0 outside the loop

Then answer me this: why do you us range()? why not simply loop over x directly, so you can add the values to ans


Thanks for the help!
placing ans = 0 outside the loop solves it.

And yea, I should have looped over x directly and save myself the hassle.
I went back to recap the past topics, so am I right to say it's more appropriate to loop over range() when we're dealing with lists?


Good to hear you solved it :slight_smile:

as for your question, that depends. If you just want to print the values in the list:

aList = ['a', 'b', 'c']
for x in aList:
    print x

i don't see why you should use range. Range gives you indexes, so range is very useful if you need to update elements in the list


ah understood. thanks for your help and clarification!



you're welcome