I have been tinkering with this code for hours. Yet, this code returns a different answer. Can anyone address what is wrong in the following code?


digit_sum returns wrong answer
For e.g:
input 123 gives 9 as output which is wrong.

def digit_sum(n):
    rem = n % 10
    s = 0
    while True:
        s += rem
        n //= 10
        if n==0:

    return s


rem will always be the same, given it is defined before the loop starts:

rem = n % 10

so if you have 434, rem will always be 4. Not sure that is the intention


Thank you Sir. That worked. But, Does python not dynamically change the value of rem?


if python just decided to just change values for you, programming becomes a really unpleasant. Why should python change values for you? It only does that when instructed


Hmm you're right. But, is there an anology of pointer variables (as in cpp) in python?


we have references in python:

i = 5     # create int(5) instance, bind it to i
j = i     # bind j to the same int as i
j = 3     # create int(3) instance, bind it to j
print i   # i still bound to the int(5), j bound to the int(3)

It is the closest thing you will get, but there are no pointers in python like in c and c++

Also, you don't need them to solve this problem


Okay. I was just asking. :smile: Thank you.