The code works correctly. However, I want to know the logic behind breaking the variable 'n' into strings instead of leaving them as integers. When I first approached this problem I didn't think of breaking it into strings. If someone could please explain the logic/reasoning behind this approach it would be greatly appreciated! You all are awesome for assisting, thanks!

#Initiate Code
def digit_sum(n):
    num=[ ]
    n = str(n) #why do we need to make the values strings?
    for i in n:
        total = 0 #initializng the variable
    print num
    for i in num:
        total += int(i)
    print total
    return total


You can't leave n as an integer because you cannot break apart an integer by character. However, strings are interpreted as an array of characters basically, so you can say

if it's a string.
If it's left as a variable,

would throw an error.
I hope this helps a little bit. :slight_smile:


You are seriously amazing!! Thank you so much, this is incredibly helpful.


No problem! I'm glad that makes sense! I'm not always the best at explaining things. :slight_smile:


def digit_sums(n):
result = 0
for i in range(len(n)):
num= int(n)%10
n =int(n)//10
result = result+num
return result

I try the challenge way to do this, but i am not sure it right or not


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.