Stuck on digit_sum


#1

I've seen this code being used as a correct answer on other posts, but whenever I try to put it in I get the error message: "Oops, try again. Your function fails on digit_sum(434). It returns 4 when it should return 11."

def digit_sum(n):
    total = 0
    for i in str(n):
        total += int(i)
        return total
print digit_sum(12345)

Is anyone else having this problem? Any help would be greatly appreciated.


#2

Problem:
the return statement placement(indentation)

hint**
The return statement should not be part of/inside of loop block.

We have to return after we add all digit values together.
Return:
When a function executes the codes inside of it and sees returns statement, it simply halts the execution and returns the value attached right to it.
also the codes after return statement are ignored in this process.

In your code, this is happening as return is part of loop, it simply runs with other code inside of loop block and as the execution hits returns, it breaks out from function without adding other digit values.


#3

thank you!!!!!!!!!!!!!!!!!!!


#4

I hope it clear that why last code did not worked out, if you still have confusion you can point them! :thumbsup:


#5

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