Digit_sum


#1



why my code is not working??Can somebody explain this


output is coming wrong


i expect to get answer


def digit_sum(n):
    digits=len(str(n))
    i=1
    while i<=digits:
        var=0
        nth=n//10**(digits-i)
        remainder=n%10**(digits-i)
        var+=nth
        n=remainder
        i+=1
    return var

n=input("Enter positive integer: ")
print digit_sum(n)


#2

this line:

var=0

by placing it inside the loop, each run of the loop var gets set back to zero, not maintaning what you add to it here:

var+=nth

place var=0 outside the loop

also, here:

n=input("Enter positive integer: ")

input() will evaluate the input as code, not a good idea. Use raw_input, which stores the result as string, you might want to convert to integer


#3

Thank you ,Sir...i understand the problem


#4

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