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


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


Try to return sum(l) instead of print it


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.


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


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