Digit sum


why is it not working??

def digit_sum(n):
  a = len(str(n))
  suma = 0
  for i in range(a):
    b = (float(n)/10 - int (n)/10)*10
    suma = suma + b
    n = int(n)/10  
  return suma

print digit_sum(434)


casting back and forth between integer and float is asking for problems. I would rethink this line:

b = (float(n)/10 - int (n)/10)*10

to find a simpler way to get the last digit.

while humans use base 10 to count, computers use base 2. So float values will not always be accurate.


So i can’t rely on float values of mathematical equations?


you can, within limits. But personally, this function has to add digits of integer values together and return an integer, then i would avoid float if possible (which is possible)


can introduction of float for even one of the values affect the whole data type of the answer?
I mean if all other values are integer, let’s say, and one is float, how does that affect the final answer of the equation?



print type(3 + 3.0)
print type(3 + 3)

type() is a built-in function which gives you the data type


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