如何在python中的递归函数中存储和处理变量?

hel*_*rld 4 python variables recursion function

我对下面的代码很困惑.

def a(x):
    print(x)    
    if x > 0:
        a(x - 1)
    print(x)    #I am confused with this print statement 

a(5)
Run Code Online (Sandbox Code Playgroud)

以上代码输出:

5
4
3
2
1
0
0
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)

直到0我理解它是如何打印的,然后是为什么它按升序打印.
可变x正在改变所以我想输出将是x的最后分配的值0.
我的预测输出:

5
4
3
2
1
0
0
0
0
0
0
0
Run Code Online (Sandbox Code Playgroud)

那么它如何跟踪 x ...的值?
有人可以简要解释递归函数中实际发生的事情以及变量如何存储在其中.

Wil*_*sem 9

您必须了解每个函数调用x都是本地的.所以这意味着第二次调用f 具有不同x.想象一下:你可以看到它:

f(x=5)
    print(x) # this x = 5
    f(x=4)
        print(x) # this x = 4
        f(x=3)
            print(x) # this x = 3
            f(x=2)
                print(x) # this x = 2
                f(x=1)
                    print(x) # this x = 1
                    f(x=0)
                        print(x) # this x = 0
                        print(x) # this x = 0
                    print(x) # this x = 1
                print(x) # this x = 2
            print(x) # this x = 3
        print(x) # this x = 4
    print(x) # this x = 5
Run Code Online (Sandbox Code Playgroud)

所以在你的递归调用中,有六个xes.每个x变量可以具有不同的值,并且将它们更深一级地更改对上面的级别没有影响,等等.