0

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

5
  • 5
    a(6) is 7, so a(a(6)) is a(7). Commented Feb 16, 2018 at 8:11
  • 2
    The innermost function is executed first. It returns 7. Then then next layer will receive 7 as its argument and return 8. etc. Python's order of operation is pretty much the same as in standard mathematical expressions. Commented Feb 16, 2018 at 8:11
  • What your are looking for is called recursion. That occurs when a function is calling itself ... Commented Feb 16, 2018 at 8:13
  • 4
    @mahatmanich This is not recursion. Commented Feb 16, 2018 at 8:13
  • @Dyz ah ok the call is just upon itself and recursion is not included in the function itself ... Commented Feb 16, 2018 at 8:14

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help! You guys are the best

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.