Digit_sum


#1




I am confused as i don't see where i am wrong. I have collected the integer and turned it into a string and then I am picking out each digit one by one, turning them back into integers and i am appending it to a list and then finally i am printing the sum of that list. Instead the code returns 'none' and this message comes up: 'Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11.' Please help. Here is my code:
Thanks for the help :slight_smile:


n=int(input('input a number'))
def digit_sum(n):
    n=str(n)
    for i in range(len(n)):
        x=0
        z=[]
        a=n[x]
        y=int(a)
        z.append(y)
        x=x+1
    print(sum(z))


#2

Define this outside of the loop so you don't keep wiping it out with each iteration.

Apart from other possible issues, this is one that can be fixed by replacing print with return.


#3

thanks. that's a rookie mistake. Darn, should've thought about it


#4

okay so it works better but now i get an error message saying:'Oops, try again. Your function fails on digit_sum(434). It returns 12 when it should return 11.' PLease help. sorry for bothering you :grin:


#5

So you have converted the number to a string. All you need now is an accumulator initialized to 0.

n = str(n)
result = 0
for i in n:
    result += int(i)

#6

thanks so much. I never knew bout accumulatr's and they are alot easier than my method. Thanks alot :slight_smile:


#7

great help, @mtf aka roy


#8

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