Digit sum


def digit_sum(n):
    for x in n:
        rem= n % 10
        x= x + rem
        n = n // 10
        return n


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



n is a number, not an iterable (string, list, tuple). To iterate over the number, convert it to a string.

for x in str(n):

However this won't jive with the methodology since you are using a mathematical approach that will work better with a while than a for.

x = 0
while n > 0:
    x += n % 10
    n //= 10


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