我需要帮助来了解 Python 的 return 语句及其在此递归语句中的作用 [英] I need help wrapping my head around the return statement with Python and its role in this recursive statement

查看:58
本文介绍了我需要帮助来了解 Python 的 return 语句及其在此递归语句中的作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不,这不是家庭作业,而是在我们的考试学习指南上.我需要了解 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.

为什么它会打印出它的作用以及最后 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>result 返回打印).相反它只是返回,因此为什么 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 

这篇关于我需要帮助来了解 Python 的 return 语句及其在此递归语句中的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆