2

I am using the simple recursive function below to add together all the digits in a number. My question is why is the initial 'return n' needed (it does not work without it) rather than just going to the n%10?

def sumDigits(n):
    return n and n%10 + sumDigits(n//10)  
sumDigits(123)

Thanks.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Jack A Roe
  • 23
  • 3

1 Answers1

3

Every recursive function must have a base case, otherwise recursion continues until you hit the limits of your stack. In this case, the base case, or the stopping point of your function, is determining that all digits have already been added (i.e., n == 0).

So,

def sumDigits(n):
    return n and n % 10 + sumDigits(n // 10)  

Can (and should) be re-written as:

def sumDigits(n):
    if n == 0: 
        return n 
    return n % 10 + sumDigits(n // 10) 

In this case, the base case has been explicitly spelled out using an if condition.

In the first case, however, the developer has taken advantage of the "truthiness" of ints and the behaviour of the and logical operator. For more information, see Strange use of "and" / "or" operator. The working of and in the first scenario is described as:

Return the first falsy value if there are any, else return the last value in the expression.

"Falsy" values include 0 and 0.0 (relevant to your problem) among other things. When n == 0, the expression short circuits and 0 is returned. Otherwise, the second expression to the right of the and is evaluated and returned.

cs95
  • 379,657
  • 97
  • 704
  • 746