Why is my recursive function returning a None value

Question:

The function takes a string value and recursively checks the length of number and breaks if it detects a space, returning the full number.

def detectNumber(stringVal,lp,makeNumber=""):
    try:
        if stringVal[lp] == " ":
        
            print("Space detected")
            
            print(f"At start makeNumber was {makeNumber}")
            return makeNumber
            
        else:
            makeNumber +=stringVal[lp]
            lp +=1
            detectNumber(stringVal, lp,makeNumber= makeNumber)
        
    except:
        print(f"Error {lp}")

Event though the print statement shows the correct value of makeNumber when i return that value it always reverts to None. Why?

Example input

detectNumber("12456  18",0)
Asked By: jyashi

||

Answers:

As you go down the call stack, you need to be returning values back up the stack once you hit the base case.

def detectNumber(stringVal, lp, makeNumber=""):
    try:
        if stringVal[lp] == " ":

            print("Space detected")

            print(f"At start makeNumber was {makeNumber}")
            return makeNumber

        else:
            makeNumber += stringVal[lp]
            lp += 1
            # Here
            return detectNumber(stringVal, lp, makeNumber=makeNumber)

    except:
        print(f"Error {lp}")
>>> detectNumber('123 ', 0)
Space detected
At start makeNumber was 123
'123'

You were getting None, because the value was only returned to the last recursive caller, rather than all the way back up the stack

Answered By: Freddy Mcloughlan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.