I wrote a simple recursive function to calculate the sum of digits of a number.
But instead of returning an integer, it prints None.

def digit_sum(n):
    if n < 10:
        return n
    
    print(digit_sum(n // 10) + n % 10)

result = digit_sum(452)
print(result)

5 Replies 5

because print returns None. Also, this should be a proper Q&A, not a "best practices" discussion

You're printing the result of the recursive call, but you're not returning it. So when digit_sum(452) finishes, it returns None because there's no return statement in the recursive branch.

Your function returns None because you never return anything in the recursive case — you only print() the result. print() displays the value but does not return it. So the function implicitly returns None.

def digit_sum(n):
    if n < 10:
        return n
    return digit_sum(n // 10) + n % 10

result = digit_sum(452)
print(result)

It's not because print() returns None, @DeepSpace! The result of print() is discarded.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.