简体   繁体   English

Python函数返回循环

[英]Python Function Return Loop

Ok, so this piece of code is from a practice question at my school. 好的,所以这段代码来自我学校的练习题。 We are to mentally parse the code and check the answer. 我们要在心理上解析代码并检查答案。

When I first parsed it, I got 4. I copied the code and ran it through IDLE and got 8. I ran the debugger and saw that the else: return is looping the if else statement until x == 0 and then it returns 1. 当我第一次解析它时,我得到4.我复制了代码并通过IDLE运行它得到8.我运行调试器并看到else:return循环if else语句直到x == 0然后它返回1 。

I do not understand how return 1 is coming out to 8. 我不明白返回1是如何出现在8。

def foo(x=5):
    if x == 0:
        return 1
    else:
        return 2*foo(x-1)

print(foo(3))

I understand that it is calling foo(x-1) inside the function foo(x=5) which makes it check if else again and again until x == 0 then it returns 1. How does return 1 end up printing 8? 我理解它在函数foo(x=5)中调用foo(x-1) ,这使得它一次又一次地检查是否为x == 0然后返回1.返回1如何最终打印8?

You will make following calls to foo: 您将对foo进行以下调用:

foo(3) -> foo(2) -> foo(1) -> foo(0)

those will return 那些会回来的

foo(0) -> 1
foo(1) -> 2 * foo(0) -> 2 * 1 -> 2
foo(2) -> 2 * foo(1) -> 2 * 2 -> 4
foo(3) -> 2 * foo(2) -> 2 * 4 -> 8

Is it clear now? 现在清楚了吗?

I think you're having the right idea (otherwise you wouldn't have gotten the answer 4), you're simply aborting too early in your mental exercise. 我认为你有正确的想法(否则你不会得到答案4),你只是在心理锻炼中过早堕胎。

You can keep track of the variables by tabulating them while going through the code: 您可以在浏览代码时通过列表来跟踪变量:

  • foo(3)
    • calls foo(3 - 1)foo(2) 调用foo(3 - 1)foo(2)
      • calls foo(2 - 1)foo(1) 调用foo(2 - 1)foo(1)
        • calls foo(1 - 1)foo(0) 调用foo(1 - 1)foo(0)
          • returns 1 返回1
        • returns 2 * foo(1 - 1)2 返回2 * foo(1 - 1)2
      • returns 2 * foo(2 - 1)4 返回2 * foo(2 - 1)4
    • returns 2 * foo(3 - 1)8 返回2 * foo(3 - 1)8

Recursion works in reverse from what you'd initially expect. 递归与您最初期望的相反。 It doesn't start with x=3, but instead it follows all the recursive calls and the first value of x is actually 0. 它不是以x = 3开头,而是跟随所有递归调用,x的第一个值实际上是0。

Here is a modified version of your script that illustrates the order of how it ran the steps and how it arrived at 8. 下面是您脚本的修改版本,它说明了如何运行步骤以及它如何到达8的顺序。

def foo(x=5):
    if x == 0:
        r = 1
        print (x, r)
        return r
    else:
        r = 2*foo(x-1)
        print (x, r)
        return r

print(foo(3))

Notice how the first value of x that's printed is 1 instead of the 3 you gave it. 注意打印的x的第一个值是1而不是你给它的3。 Once you understand this, you will understand recursion. 一旦你理解了这一点,你就会理解递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM