我需要帮助来理解使用 Python 的 return 语句及其在此递归语句中的作用

2022-01-19 00:00:00 python 递归 return printing

问题描述

不,这不是家庭作业,而是在我们的考试学习指南中.我需要了解 return 语句所扮演的角色以及递归所扮演的角色.我不明白为什么函数在 x = 1 之后不会中断.

No this isn't homework but it is on our study guide for a test. I need to understand the role the return statement plays and the role recursion plays. I don't understand why the function doesn't break after x = 1.

def thisFunc(x):
    print(x)
    if x>1:
         result=thisFunc(x-1)
         print(result)
    return x+1

抱歉,我知道这是多么简单,但我真的需要一些帮助.可能是为什么我在任何地方都找不到解释……因为它太简单了.

Sorry, I understand how elementary this is but I could really use some help. Probably why I can't find an explanation anywhere...because it's so simple.

edit:为什么它会打印出它的作用以及最后的 x 值是什么以及为什么?对不起,如果我问了很多,我只是很沮丧

edit: Why does it print out what it does and what and why is the value of x at the end? sorry if I'm asking a lot I'm just frustrated


解决方案

当你输入带有值 n>1 的函数时,它会打印当前值,然后用 调用它自己n-1.当内部函数返回时,它返回值 n - 1 + 1,即 n.因此,该函数两次打印出 n 值,一次在内部递归之前,一次在之后.

When you enter the function with a value n>1 it prints the current value, and then calls it's self with n-1. When the inner function returns it returns the value n - 1 + 1 which is just n. Hence, the function prints out the value n twice, once before the inner recursion and once after.

如果 n == 1,这是基本情况,该函数只打印一次 1 并且不会再次调用它自己(因此不会得到 结果返回打印).相反,它只是返回,因此 1 只打印一次.

If n == 1, which is the base case, the function only prints 1 once and does not call it self again (and hence does not get result back to print). Instead it just returns, hence why 1 is only printed once.

把它想象成洋葱.

调用 thisFunc(n) 将导致

n
# what ever the output (via print) of thisFunc(n-1) is
n 

相关文章