非常基本的问题,因为我完全不熟悉这些概念。我将此头递归函数放入Python Tutor中以更好地了解发生了什么-为什么该函数甚至在非常结束之前都没有触摸print('递归调用后计数:')。后续问题-为什么在遍历if语句的返回部分后,数字然后按顺序打印?
我觉得我在这里想念一些超基本的东西/对它哈哈了
PS。如果在帖子中发现这种方式,请原谅超级糟糕的格式,这对我是陌生的。
def head_recursion(count):
if count <= 0:
print('Base case reached! HEAD RECURSION')
return
head_recursion(count-1)
print('Count after recursive call:',count)
def main():
print('Executing head_recursion(3)...')
head_recursion(3)
main()
答案 0 :(得分:0)
因为递归调用必须先完成(达到基本情况)才能返回,直到返回为止,其下的打印无法运行。
def head_recursion(count):
if count <= 0:
print('Base case reached! HEAD RECURSION')
return
# Execution gets to here, then makes a recursive call.
# It can't continue past here until the recursive call it made returns
head_recursion(count-1)
print('Count after recursive call:',count)
就像其他任何代码一样
y = some_function()
print("Reached") # This won't run until some_function has returned