I'm not sure which part of the line you don't understand since you didn't specify, but I'm going to assume it's one of:
- modulo operator (%);
- integer division operator (//); or
- recursion
(1) is easily googled, and there are plenty of good explanations (for example, the first line in Wikipedia article here): "In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus)."
(2) See this stack overflow post for an explanation of the // operator.
(3) A function calling itself, as this one does, is an example of recursion, and the function is said to be a "recursive function." A key component of a recursive function is the "base case," a case where the function does not call itself. Without a base case calling the function once would enter into an infinite loop where the function calls itself forever. The if-statement in this code defines a base case.
A common pattern in recursion is, on the recursive call, to pass to the function an argument that is "simpler" than the argument it received (in that it is "closer" to the base case).
Let's run through a quick example. If I call numbersum(123)
:
- Is
123 == 0
? No. So, numbersum(123)
equals 123%10
, which is 3, plus numbersum(123//10)
, which is numbersum(12)
.
- Now we have to figure out
numbersum(12)
. Same steps. Is 12==0
? No. So, numbersum(12)
equals 12%10
, which is 2, plus numbersum(12//10)
, which is numbersum(1)
.
- So what is
numbersum(1)
? Same steps. Is 1==0
? No. So, numbersum(1)
equals 1%%10
, which is 0, plus numbersum(1//10)
, which is numbersum(0)
.
- Lastly, what is
numbersum(0)
? Is 0==0
? Yes! The base case is hit here. So numbersum(0)
equals 0.
If you look back through these steps, you will see that
numbersum(123) = 3 + numbersum(12)
numbersum(12) = 2 + numbersum(1)
numbersum(1) = 1 + numbersum(0)
numbersum(0) = 0
Working youre way back up the chain using basic algebraic substitution, you get the correct answer: 6.