我正在试着理解递归,当我写一小段代码时,我不知道它是如何到达特定输出的。
x = 0
def recursion():
global x
x += 1
print(x)
while x < 5:
recursion()
recursion()
print("example")
print("test")
recursion()
输出:
1
2
3
4
5
test
6
test
example
test
7
test
example
test
8
test
example
test
9
test
example
test
如果有人能一步一步地解释一下,我将不胜感激。
发布于 2018-07-15 03:34:00
这是一步一步发生的事情。第一次呼叫时:
def recursion():
global x
x += 1
print(x) # x ==1
while x < 5:
recursion() # on hold, executing recursion
def recursion():
global x
x += 1
print(x) # x ==2
while x < 5:
recursion() # on hold, executing recursion
.
.
.
.
def recursion():
global x
x += 1
print(x) # x == 5, skipping while loop
while x < 5:
recursion()
print('test') # printing test
现在恢复所有处于保留状态的呼叫:
def recursion():
global x
x += 1
print(x)
while x < 5:
recursion() # Called when x == 1
recursion() # Resuming, this will put x to 6 and print it, won't enter the loop, so prints test directly
print('example') # print example
def recursion():
global x
x += 1
print(x)
while x < 5:
recursion() # Called when x == 2
recursion() # Resuming, this will put x to 7 and print it, won't enter the loop, so prints test directly
print('example') # print example
直到调用where x==4
https://stackoverflow.com/questions/51342707
复制相似问题