Digit_sum


#1



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?

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#

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:
            break

    return s


#2

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


#3

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


#4

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


#5

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


#6

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


#7

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