Skip to content
Advertisement

Python Return Command In Recursion Function

While learning Python and browsing the internet I stumble upon a piece of code in w3schools.com. I tried to run it using their built-in site Python IDLE and using my own Python 3.9.0 Shell. What I got is two different outputs.

I want to know which output is the correct output and why is it providing two different outputs.

The Codes and Its Output

Built in site Python IDLE Built in site Python IDLE

Python 3.9.0 Shell Python 3.9.0 Shell

Notice that the number 21 is only printed(outputted) once when running the code using Built-in site Python IDLE, while it is printed(outputted) twice when running the code using Python 3.9.0 Shell.

My Own Debugging

I have tried a simple print statement debugging. Checking the result there is only one different, using Python 3.9.0 Shell the last return line is executed and it outputted the last result while using the Built-in site Python IDLE the last return is either not executed or not outputted, in this case, I believe it is the former, and I believe the correct output is the Python 3.9.0 Shell, but I have no idea why are there two different output.

Print Statement Using Python 3.9.0 Shell Result Part 1 Result Part 2

Print Statement Using Built-in site Python IDLE Result Part 1 Result Part 2

Source Code

def tri_recursion(k):
    if(k>0):
           result = k + tri_recursion(k-1)
           print(result)
    else:
           result = 0
    return result

tri_recursion(6)

Advertisement

Answer

You have added a return result statement at the end. For any IDE, unless you print that value, it wouldn’t be displayed. However, IDLE prints the return value as well. Technically, both outputs are correct, since both interpreters are configured to do different actions. As a small example,

def foo():
    return(1)

Running foo() on IDLE gives >>> 1, whereas it gives nothing on other IDE’s, as there is no print statement

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement