I've tried this but it doesn't work.
def sumDigits(n):
if n == 0:
print 0
else:
print n%10 + sumDigits(n/10)
sumDigits(35)
I've tried this but it doesn't work.
def sumDigits(n):
if n == 0:
print 0
else:
print n%10 + sumDigits(n/10)
sumDigits(35)
If you are using Python 3.x, note that you need to use // to perform integer division, as / will perform float (true) division even with two integers.
In any case, the function needs to return the values, not just print them.
def sumDigits(n):
if n == 0:
return 0
else:
return n%10 + sumDigits(n//10)
Then it will work as intended
>>> sumDigits(35)
8
Here is a solution that works for numbers (and strings!) of all lengths.
def sumDigits(n):
n = str(n)
if n is "":
# Base Case: Return 0 when there is nothing left
return 0
else:
# Default Case: Return the first number + sum of the rest)
return int(n[0]) + sumDigits(n[1:])
>>> print sumDigits(359)
>>> 17
This, when written out, will look like this:
sumDigits(359) = 3 + sumDigits(59) = 3 + 5 + sumDigits(9) = 3 + 5 + 9 + 0
You need to return values instead of printing values.
Try this:
def sumDigits(n):
if n == 0:
return 0
else:
return n%10 + sumDigits(n//10)
>>> sumDigits(41)
5
>>> sumDigits(31)
4
You can also use and operator to leverage the equality check when n is 0.
def sumDigits(n):
return n and n%10 + sumDigits(n//10)
Here, n%10 + sumDigits(n//10) will be evaluated only when n is non-zero.
Use // as it gives the quotient on division in which the digits after the decimal point are removed.
When you attempt to make the recursive call sumDigits( n / 10) it expects to have a value returned. When it fails to get that value because the function doesn't return anything, you receive the error.
This could prove useful: Python Functions