# Digit_sum challenge seems to be going okay in terminal but not in codecademy?

#1

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#

Hi everyone,

for the exercise digit_sum I wrote the following code:

``````digits = []
def digit_sum(n):
print("start")
digits.append(n % 10)
next_digit = n // 10
if next_digit == 0:
print("stop")
print(sum(digits))
return sum(digits)
print("reload")
digit_sum(next_digit)``````

If I type this into a terminal, I get :
digit_sum(434)
start
reload
start
reload
start
stop
11

but in codecademy it says: Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11.

Thanks for your help

Cheers,
Jonas

#2

That is because the return statement must not be encountered.

#3

is this because the function recalls itself, like a recursive function?
the print("stop") is shown so, the return must be reached too?

#4

when you are using recursion, you should make sure that each function call always returns something.
In your implementation, only the last call `digit_sum(4)` will return because after the division `next_digit == 0` becomes true.
the previous calls `digit_sum(434)` and `digit_sum(43)` will not return anything.
Also, this can be done better with a loop.
Hope this helps!
Edit: if you want to use recursion, I believe you should write your last line as `return digit_sum(next_digit)`

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.