-1

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

anyone
  • 37
  • 5

1 Answers1

0

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))
Ohad Sharet
  • 1,097
  • 9
  • 15