Digit_sum - I got the answer, but it won't accept it


#1

Here's my code.
def digit_sum(n):
n = str(n)
l = []
for i in range(len(n)):
l.append(int(n)%10)
n = int(n)//10
n = str(n)
print sum(l)


#2

Try to return sum(l) instead of print it


#3

Wow, thank you ! That's my solution .

def digit_sum(n):
n = abs(n)
sum = 0
while n > 0:
sum += n % 10
n = n // 10
return sum

Before reading you comment I've used 'print sum', and I have just realised my error :smiley: It appears that it prints 0 instead of the result from the while loop. Thank you again !

Btw, I have no idea why does everyone want to convert the number into a string and vice versa.


#4

We convert it to a string so we can use len():.


#5

in addition to @ajaxwhiz08742 strings are iterables in python meaning we can loop over them. so when we convert the number to string we can iterate it and get each character, convert them to digits and add to sum


#7