Digit_sum


#1




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:
        num.append(i)
        total = 0 #initializng the variable
    print num
    for i in num:
        total += int(i)
    print total
    return total


#2

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:


#3

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


#4

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


#6

def digit_sums(n):
n=str(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


#7

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