# Sum of digits

#1

Below is the link of code I am stuck at:

I am getting the below error:
File “python”, line 13
return sum_digits
^
IndentationError: unexpected indent

I was expecting it to run successfully. I have tried so many times but the code is keeping on throwing indentation errors.

``````
Below is the code I have written:
def digit_sum(n):
sum_digits = 0
if n < 0:
print "This is a negative no."
return
elif n == 0:
return 0
else:
while n > 0:
rem = n % 10
sum_digits += rem
n /= 10
return sum_digits

``````

Someone please suggest what can be the mistake that is throwing the “Indentation error” here?

#2

this two lines:

``````      n /= 10
return sum_digits
``````

don’t have the same indent level, why?

#3

Yes, I agree they don’t have the same indent level but if you see carefully it’s just after a loop so if I keep it on the same indent level, result will be returned before I even completed the loop. And on your suggestion I tried the same as well, but the error is same.

#4

Everyone may feel differently about this, but I like a function to return without printing, and then print the return value at the caller.

``````print (digit_sum(-1234))    # This is a negative number.
``````

In other words,

``````return "This is a negative number."
``````

Since you have set `sum_of_digits` to `0`, then when your final return statement is outside of the if statement, it will return 0 if the loop does not run. This `elif` is not necessary.

Note that in Python 2 (used here) this will be an integer, but in Python 3 it will be a float. Suggest use floor division, instead so it will work correctly in both versions.

``n //= 10``

#5

def digit_sum(n):
sum_digits = 0
while n > 0:
rem = n % 10
sum_digits += rem
n //= 10
return sum_digits

print digit_sum(0)
print digit_sum(5937)
print digit_sum(67392722)
print digit_sum(5)

I tried changing the code. But it is still not working. When I put return at the same level as the function is throws “return outside function” and if I put it at the same level as while loop it throws “Indentation error”.
It’s difficult to figure out what can be corrected here?

#6

Because it needs the same indentation as the first line (sum_digits = 0).

``````def digit_sum(n):
sum_digits = 0
while n > 0:
sum_digits += n % 10
n //= 10
return sum_digits
``````

#7

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