How does return statement with recursion calls hold intermediate values in Python?

后端 未结 2 339
鱼传尺愫
鱼传尺愫 2021-01-15 08:41

Was reviewing some python code related to recursion calls and noticed the return statement looked interesting. How does the recursion work when there is no variable assignm

相关标签:
2条回答
  • 2021-01-15 08:51

    As explained by AChampion if you want to see the same kind of stack trace for your code in Pycharm do few steps .

    In Pycharm select

    Then you can see while debugging each step how the call stack is added and once the operation is done how the values are returned

    0 讨论(0)
  • 2021-01-15 09:15

    The function returns the value to the call higher in the call stack, why do you think it needs a variable, e.g. take a simple recursive call:

    def r(n):
        if n == 0:
             return 0
        return 1 + r(n-1)
    

    Then the call stack would look like:

    r(3):
        return 1 + r(2)
        r(2):
            return 1 + r(1)
            r(1):
                return 1 + r(0)
                r(0):
                    return 0
    

    So when you unwind the call stack you get:

    r(3):
        return 1 + r(2)
        r(2):
            return 1 + r(1)
            r(1):
                return 1 + 0
    --
    r(3):
        return 1 + r(2)
        r(2):
            return 1 + 1
    --
    r(3):
        return 1 + 2
    --
    3
    
    0 讨论(0)
提交回复
热议问题