简体   繁体   中英

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.

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.

I understand the function. It has a name of a, and takes one argument, x. If I did a(6) I'd expect 7 to be returned. It's the a(a(a(6))) that confuses me - all of the a's and parentheses.

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.

The image included in your question exactly describes this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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