2024-04-18 07:32:03 发布
网友
我有密码:
def recursion0(x): if x == 1: return 1 else: recursion0(x-1) print x
我知道值2-x会打印出来,但我不知道如何映射调用堆栈。下面是我的想法。你知道吗
设x=3。3在递归0(3-1)中转到2,然后2在递归0(2-1)中转到1。然后1返回到调用它的函数recursion0(2-1),然后2因为是x值而被打印?这张so 3打印出来后会发生什么? 另一个问题,为什么x在返回1之后(而不是之前)打印?你知道吗
对recursion0(3)的调用不会返回1,而是None,因为else路径不会返回任何内容。你知道吗
recursion0(3)
1
None
要修复它,请将recursion0(x-1)更改为return recursion0(x-1)。你知道吗
recursion0(x-1)
return recursion0(x-1)
由于print在递归之后,打印顺序与调用顺序相反。你知道吗
print
I want values from 1-x printed, and how does this process work?
def recursion0(x): if x == 0: return recursion0(x-1) print (x) recursion0(3)
输出为:
>>> 1 2 3
对
recursion0(3)
的调用不会返回1
,而是None
,因为else路径不会返回任何内容。你知道吗要修复它,请将
recursion0(x-1)
更改为return recursion0(x-1)
。你知道吗由于
print
在递归之后,打印顺序与调用顺序相反。你知道吗输出为:
相关问题 更多 >
编程相关推荐