Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to return a value from recursive function in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading