简体   繁体   English

这个Python函数如何运作?

[英]How does this Python function work?

I'm going through an MIT open courseware class right now for Python, and I'm not understanding how this function is returning 9. 我现在正在通过MIT开放课件类供Python使用,并且我不了解此函数如何返回9。

def a(x):
   '''
   x: int or float.
   '''
   return x + 1

a(a(a(6)))

The above returns 9. I've went through it step by step using pythontutor (Visualize Python) and I'm still not understanding. 上面的返回值为9。我已经使用pythontutor(Visualize Python)逐步进行了测试,但我仍然不了解。

I understand the function. 我了解功能。 It has a name of a, and takes one argument, x. 它的名称为a,并带有一个参数x。 If I did a(6) I'd expect 7 to be returned. 如果我执行了(6),我希望返回7。 It's the a(a(a(6))) that confuses me - all of the a's and parentheses. 是让我感到困惑的a(a(a(a(6))) -所有a和括号。

How is this working? 怎么运作的? Maybe a step by step sequence of what each a means, etc. 也许一步步的每个什么手段等接续步

Based from your replies, is this what you mean? 根据您的答复,这是什么意思?

描述过程的图像

You can see it as 你可以看到它

x = a(6) # returns 7
y = a(x) # returns 8
z = a(y) # returns 9

In both cases, the result of the function is used für the next function call, and this result for the next again. 在这两种情况下,该函数的结果都将在下一个函数调用中使用,并且此结果将再次用于下一个函数调用。

The first function call turns 6 into 7, the second 7 into 8 and the third and last turns 8 into 9. 第一个函数调用将6变为7,第二个函数将7变为8,第三个和最后一个将8变为9。

The image included in your question exactly describes this. 您的问题中包含的图像准确地描述了这一点。

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

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