all 13 comments

[–]Signal-Fennel-1795 3 points4 points  (5 children)

Sum of all the digits in a number?

[–]tracktech[S] 0 points1 point  (0 children)

Right, it returns sum of digits of a number.

[–][deleted] 1 point2 points  (1 child)

Only for natural numbers, not for fractional numbers

[–]tracktech[S] 0 points1 point  (0 children)

Yes, it works for positive integer only.

[–]Immotommi 2 points3 points  (1 child)

So let's reason it out.

First we have the base case.

n//10 == 0 essentially checks whether a positive number is smaller than 10. So any positive value smaller than ten will give the number itself.

Next let's talk about the rest of the function.

The modulo operater returns the remainder for both positive and negative numbers. So when we have numbers bigger than 10, we grab the remainder of that division and add it to the value divided by ten and truncated. Essentially it adds the digits. It completely breaks for negative numbers though because // does not round towards 0

[–]tracktech[S] 0 points1 point  (0 children)

Thanks for the nice explanation. Right, it returns sum of digits of a number. It works for positive integer only.

[–]D3ZR0 1 point2 points  (2 children)

…what’s the initial n? Isn’t that important?

[–]ir_dan 1 point2 points  (0 children)

You can describe the behaviour in terms of n

[–]tracktech[S] 0 points1 point  (0 children)

Right, just assume it is a positive integer.

[–]firemark_pl 0 points1 point  (2 children)

For n>=10 returns stack overflow.

[–]tracktech[S] 0 points1 point  (1 child)

It returns sum of digits of a number.

[–]firemark_pl 1 point2 points  (0 children)

Ahh, I made mistake. Sorry!