Sum_digit what is wrrong woth my code?


def digit_sum(n):
    if len(str(n)) > 1:
        for i in len(str(n)):
            sum += int(str(n[i]))
            return sum
        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.



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


good point, and I still have some problem


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)


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