Sum_digit what is wrrong woth my code?


#1



def digit_sum(n):
    if len(str(n)) > 1:
        for i in len(str(n)):
            sum += int(str(n[i]))
            return sum
    else:
        print n
    print digit_sum(12345)

Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a "'int' object is not iterable" error.


#2

here:

for i in len(str(n)):

why use len()? casting it to string is good, then you can loop over n, but i don't see why you would use len then


#3

good point, and I still have some problem


#4

i now contains values of the list, not indexes so you can just add int(i) tot sum

then after the loop, return the sum (containing the total)


#5

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