Stryfe
Stryfe

Reputation: 3

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?

image describing the process

Upvotes: 0

Views: 64

Answers (1)

glglgl
glglgl

Reputation: 91139

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.

Upvotes: 5

Related Questions