why is it not working showing the error #Your function fails on digit_sum(434). It returns 4 when it should return 11. def digit_sum(x): sum = 0 while(x > 0): x = x % 10 sum += x x = x/10 return sum
def digit_sum(n): sum = 0 for x in str(n): result += int(x) return result print digit_sum(20)
You dont need a while loop using a for loop for small bits of code is much easier and practical. I modified your code to work with a for loop
I see that you are trying to do this harder way.
I have modified your code a bit and it worked for me
def digit_sum(n): sum = 0 while (n>0): x = n % 10 sum += x n = n//10 return sum
Also floor division requires two slashes.
hey, i too got the answer but why n/10 do not work as in other languages dividing a INTEGER number BY 10 should give like as 156/10 = 15 and what it differs in python with floor division 156//10 = 15, do we seriously need such crazy operators i wonder. I would love the your answer. Thnq by the way.
The easiest answer I have found is here
By using n/10 in your example you will get 15.6 not 15. And as you will see in the answer from the link, floor division (//) cuts the part after the period so it leaves 15.
here is my solutions for this practice
def digit_sum(n): result = 0 num = str(n) for i in range(0,len(num)): result += int(num[i]) return result def digit_sum(n): result = 0 for digit in str(n): result += int(digit) return result