how to return a value from recursive function in python

Question:

If I have a recursive function and want to return a value when the function stops, the function terminates as intended but instead of returning the value, the function returns None. I have simplified this problem and just wrote this function:

def count(iteration):
    print(iteration)
    if iteration <= 0:
        return True
    count(iteration-1)

print(count(3))

It prints 3, 2, 1, 0 like it is supposed to and it also runs the return but it doesn’t return the wanted value (True) and instead returns None

Asked By: anyone

||

Answers:

You need to return the recursive call.
Right now your code will start by checking if iteration <= 0 and if it’s not it will call count(iteration-1) but won’t return the value of the call
and that’s why you get None for calling this function.

This should do the trick:

def count(iteration):
    print(iteration)
    if iteration <= 0:
        return True
    return count(iteration-1)

print(count(3))
Answered By: Ohad Sharet
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.