How to wite digit_sum?

#1

Hello! I write this code:

``````def digit_sum(n):
res = 0
ints = []
if n >= 0 and n - float(n) == 0:
n = str(n)
i = 0
in1 = 0
while i != len(n) - 1:
ints.append(n[i])
i += 1

while in1 != len(ints) - 1:
res = res + ints[in1]
in1 += 1
else:
print res``````

and got this message:

"list index out of range error"

Where I made a mistake? I absolutely don't understand how to write this program. Help me, please if you can.

#2

Haw, my code is a good ilustration how you shouldn't write your code. All much simplier:
`def digit_sum(n): n = str(n) total = 0 for item in n: item = int(item) total = total + item return total`

#3

you could still make your code work, just a few small changes have be made, starting here

``while i != len(n) - 1:``

why `-1`? this will cut off the last character. remove the `-1` from both loops.

then this line:

``res = res + ints[in1]``

the items stored in the list are strings, you will need to convert them to integer to before adding them to res:

``int(ints[in1])``

then all left to do is return `res` after the loop (not just print it)

then optimization would be a good idea.

#5

A post was split to a new topic: Float to int transformations drive me crazy

#7

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