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):
    for i in range(len(n)):


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.


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


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:


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)


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


great help, @mtf aka roy


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