Digit_sum


#1


Oops, try again. Your function fails on digit_sum(434). It returns 4 when it should return 11.

I get the error that says it returns 4 instead of 11. Also I tried using "while" instead of "if" in line 6, but it goes to infinite loop. What is my mistake? Where should I correct it.


def digit_sum(n):
    n = int(n)
    sums = 0
    rem = n % 10
    quo = n // 10
    if (quo > 9):
        n = rem
        sums = sums + rem
    return sums


#2

you will need a loop, otherwise you will get the sum of 4 while you should get the sum of 434, can i see how you made the loop?

if you just replace if with while, how is the loop ever going to evaluate to false? instead of quo, simply update n with floor division inside the loop


#3

This can be done with a while loop and assign the value of quo to n after

Whenever the remainder equals quotient, the loop should terminate. I did this with an if and break
In my case, I have used a variable x in place of n
Here is a part of my code:

>   x = n
>   while x > 0:
>         rem = x%10
>         total = total + rem
>         quo = x//10
>         x = quo
>         if rem == quo:
>             break

#4

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