Digit sum


#1

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)

#2

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.


#3

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


#4

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)


#5

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?


#6

yes:

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

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


#7

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