Digit_sum What did I miss?


#1

HI All,

I've revised my code so many times, can't get it right. Am I in the right direction at all?

def digit_sum(n):
n = str(n)
for item in n:
total = 0
item = int(item)
total = total + item
print total

Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11.


#2

W8 m8. What does your code do in effect? You have forgot what your code has to do.
As first, syntax errors and stuff.

  1. Declare total before for- loop -
  2. Don't give n a value -
  3. You must do this with a while loop instead of for loop -

If you did these, add a while loop. While n is higher than 0, it should add n % by 10 to total.
After it, divide ( /= ) n by 10 and return total.


#3

def digit_sum(n):
x = str(n)
total = 0
for i in x:
i = int(i)
total += i
return total

this works for me


#4

Thanks! I think I pretty much did the same as you, of course with different variable names. and that you used total += i
I don't see any other difference.
I also changed the total = 0 to get ahead of the loop.
So maybe these 2 things did the trick! Thanks!


#5

def digit_sum(n):
sum = 0
sum += n % 10
for each in str(n):
n = n // 10
sum += n % 10
return sum

I tried to do the challenging way and this worked for me.


#6

Look, I've done another way and it works, groovy !

def digit_sum (n):
n = abs(n)
n = str(n)
result = 0
liste = []
for i in n:
liste.append(i)
for x in liste:
result += int(x)
return result


#7

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