Search code examples
pythonrecursionreturn

In Python, how do I return a value from a function when an `if` statement is executed?


In this function, I want to return a value when the if statement is executed.

Since Python always returns something, it returns None.

def Persistence(number, counter):
    numArr = [int(i) for i in str(number)]
    result = 1
    data = None
    for j in numArr:
        result *= j
    if len(str(number)) == 1:
        data = str(f'Done. {counter} steps taken')
        print(data)
        # return data
    else:
        counter = counter + 1
        Persistence(result, counter)
    # return data

print(Persistence(333,0))

Maybe I put the return keyword in the wrong place (I checked by putting it in two different places, marked as a comment) or something else, but I couldn't figure it out.

Please help me out. Also, if there is another way to count the recursion steps besides my technique, please let me know.


Solution

  • Maybe try this :

    def Persistence(number, counter):
        numArr = [int(i) for i in str(number)]
        result = 1
    
        for j in numArr:
            result *= j
        if len(str(number)) == 1:
            return str(f'Done. {counter} steps taken')
    
        counter = counter + 1
        return Persistence(result, counter)
    
    print(Persistence(333,0))
    

    Hope it helps