Digit_sum


#1

hi,

the instrucions are:
Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number's digits.

For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4.

(Assume that the number you are given will always be positive.)

this is my code:


def digit_sum(n):
    y = str(n)
    summa = 0
    for ch in y: 
        f = summa + int(ch)
        summa.append(f)
        return summa

thank you for your help


#2

why this line:

summa.append(f)

append() is for adding to list, you don't have a list?

to get the total, just add int(ch) to summa + current value of summa (updating summa variable), you think you can sort this out? Look:

a = 5
a = a + 5
print a

then after the loop, return summa, by placing return inside the loop, the loop breaks in its first run. You need to let the loop finish running before return summa (the total)


#3

thank you very much I got it!


#4