0
def myfun1(count):
    count += 1
    if count == 10:
        return count
    print(count)
    myfun1(count)

if __name__ == '__main__':
    print(myfun1(0))

I want to return the count and terminate the recursion when count == 10. The above code returns None when count == 10. Could someone please elaborate?

  • I've written a statement to return count. Where is the value in count being returned? – Alpha々 Reaper Jan 25 '23 at 15:54
  • 1
    You should replace `myfun1(count)` by `return myfun1(count)`. Otherwise you completely ignore and discard the returned value of the recursive call, and don't return anything. – Stef Jan 25 '23 at 15:56

2 Answers2

0

Instruction myfun1(count) performs a recursive call but you don't do anything of the value returned by this call. You need to return a value when you reach the end of your function. Otherwise, when the end of the function is reached, you have an implicit return None statement.

So if you want to return the result of your recursive call, do something like that:

def myfun1(count):
    count += 1
    if count == 10:
        return count
    print(count)
    result = myfun1(count)
    return result

if __name__ == '__main__':
    print(myfun1(0))

Generally speaking when a function (recursive or not) is supposed to return something that it computed, make sure that it ends with a return statement.

qouify
  • 3,698
  • 2
  • 15
  • 26
0

First you need Else to return a different value in return, instead you will always return 10 in your recursion

def myFun1(count):
   count += 1
   if count == 10:
       return count
    else: 
       return count

and you have refactore some points of your function to make the recursion, call it again

def myFun1(count):
   count += 1
   if count == 10:
       return count
   else:
      count_res = myFun1(count)
      return count_res

and you have just call the function

if name == 'main': print(myFun1(0))

GuiNobre
  • 5
  • 2