0

I am not understanding how recursion works. The base case runs last, and yet the return value is None. How come?

def simpleRecursion(myString) :
    print (myString);
    if len(myString) == 0 :
        # base case
        return "base";
    else : 
        # recursive step
        simpleRecursion(myString[1:])

result = simpleRecursion("abcdefg");
print(result);
2
  • 1
    You don't actually return in your else clause. Commented Aug 14, 2014 at 19:21
  • 1
    Neither of the answers explicitly says this, so in case you didn't know: whenever you fall off the end of a function without hitting a return statement, the function returns None. Commented Aug 14, 2014 at 19:23

2 Answers 2

4

You have to explicitly return in your else clause, otherwise the return value will be lost:

else: 
    # recursive step
    return simpleRecursion(myString[1:])
Sign up to request clarification or add additional context in comments.

Comments

3

It returns None because you only return a value if the length of the argument is 0, i.e. the argument is an empty string. In the recursion simpleRecursion(myString[1:]) may return a value, but you never use it. Thus, simpleRecursion does not return a value at all, unless the argument is an empty string. Replace simpleRecursion(myString[1:]) with return simpleRecursion(myString[1:]) to fix this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.