如何在python的递归函数中存储和处理变量? [英] how variables are stored and treated in recursion function in python?
问题描述
我对下面的代码很困惑.
I am quite confused with the code below.
def a(x):
print(x)
if x > 0:
a(x - 1)
print(x) #I am confused with this print statement
a(5)
上面的代码输出:
5
4
3
2
1
0
0
1
2
3
4
5
直到 0
我都知道它是如何打印的,但是为什么它以升序打印.
可变的 x
正在更改,因此我认为输出将是x的最后分配的值,即 0
.
我的预期输出:
Up till the 0
I understand how it prints, but then why it prints in ascending order.
Variable x
is changing so what I thought the output would be is the last assigned value of x that is 0
.
My predicted output:
5
4
3
2
1
0
0
0
0
0
0
0
那么它如何跟踪 x ...的值?
有人可以在简要中解释递归函数中的实际情况以及变量如何存储在其中.
So how does it track the value of x...?
Can someone explain in brief what actually happens in recursive functions and how variables are stored in it.
推荐答案
您必须了解,对于每个函数调用, x
是本地的.因此,这意味着对 f
的第二次调用具有不同的 x
.要形象化:您可以看到它:
You have to understand that for each function call the x
is local. So it means that the second call to f
has a different x
. To visualize this: you can see it like:
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
因此,在您的递归调用中,有六个 x
es.每个 x
变量可以具有不同的值,并且将其更深地更改一个级别不会影响上面的级别,等等.
So in your recursive calls, there are six x
es. Each of the x
variables can have a different value and changing them one level deeper has no impact on the level above, etc.
这篇关于如何在python的递归函数中存储和处理变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!