1

I am currently trying to develop a recursive function in python, but I am running into issues when I try to call my return statement.

As a dummy example I wrote a simple function (shown below). When I run this function with the default argument, I can see that it indeed first executes that "else" statement several times and stops when the "if" cell condition is reached (so it seems that the "return" is executed, right?).

However, if I check my return argument, it appears that a None argument is returned.

Question: What is the correct way to get the value of "counter" exported from this recursive function?

def recursive_count(counter=1):
    if counter >=10:
        print("Final count reached.")
        return counter
    else:
        print("increasing counter.")
        counter += 1
        recursive_count(counter=counter)

Thoughts and thingsI tried:

  • My first idea was that the "print" statements were to blame. However removing them did not solve the issue.
  • Reversing the if and else statements also did not work and invoked the same behavior.
  • The fact that the function stops after 10 runs means that the "return" statement is reached. Another idea might be that it is a "scoping issue". However moving "counter" outside of the function did not work as it gave reference errors.

Use case: The idea is to use this function to automatically unfold a paginated API response.

Nick
  • 125
  • 10

2 Answers2

2

try this:

def recursive_count(counter=1):
    if counter >=10:
        print("Final count reached.")
        return counter
    else:
        print("increasing counter.")
        counter += 1
        return recursive_count(counter=counter)

I will react to your questions in comments.

Jakub Dóka
  • 2,477
  • 1
  • 7
  • 12
2

Simply add return in front of the recursive call.

return recursive_count(counter=counter)
topoly
  • 301
  • 2
  • 5