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.