15,743,609 members
1.00/5 (1 vote)
See more:
trying to write recursive function in Python to find the sum of digits of a number. Name the function sum_of_digits. my function should use recursive algorithm. i want the function to print out the sum of all the digits of a given number. For example, sum_of_digits(343) should have a output of 10.

i know that we are supposed to add an if loop for it to be recursive

Output i'm trying to achieve: 10

What I have tried:

```<pre>def sum_of_digits(n):
if n ==  :
return n
else:
return (n % 10) + sum_of_digits(n // 10)
sum_of_digits(343)```

here is what i have implemented. i do not know what to compare 'n' with? i'm stuck at the first if
Posted
Updated 4-Feb-20 3:38am
v2
Patrice T 4-Feb-20 6:08am
Where are you stuck ?
phil.o 4-Feb-20 6:35am
Do it by hand with a pen and piece of paper first. You will never learn to build an algorithm by asking other people to do it for you.

Solution 1

Hint: at each step, you may use the modulo operator (e.g. `n % 10` ) to get the last digit of the number (stop if it is `0`) and add it to the sum. Then call the next step passing ( `n // 10` ).

Richard MacCutchan 4-Feb-20 7:01am
+5; I couldn't work it out until I saw your suggestion.
CPallini 4-Feb-20 9:58am
I have to admit, recursion still doesn't come naturally to me.

Solution 3

Another way to end the loop is:
PHP
```if n < 10  :
return n
```

Nota: Using a recursive function is good only when learning recursion. For such a problem, a loop in a function is using no more code, is faster at runtime and use less resources.

CPallini 4-Feb-20 9:57am
Indeed. Have my 5.
Patrice T 4-Feb-20 9:59am
Thank you

Solution 2

```def sum_of_digits(n):
if n ==  :
return n
else:
return (n % 10) + sum_of_digits(n // 10)
sum_of_digits(343)```

here is what i have implemented. i do not know what to compare 'n' with? i'm stuck at the first if

Richard MacCutchan 4-Feb-20 9:15am
```    if n ==  0:
return n
```