0

Given the following code

def alpha(num, proc):

    def beta(): print(num)

    if num == 1:
        alpha(2, beta)
    else:
        proc()

def gamma():
    pass

alpha(1, gamma)

I expected the output to be 2, since my logic was:

   alpha(1, gamma)
=> alpha(2, beta)  # since num == 1
=> proc()          # since num != 1
=> beta()
=> print(2)        # since beta was a parameter alongside 2

However, the actual output is code is 1. Could anyone please explain why this is the case?

1 Answer 1

0

When alpha(1, gamma) is called, alpha(2, beta) is called since num is equal to 1. Here, it passes a reference to the beta function currently defined inside this invocation of the alpha function which holds a closure over the values of the parameters. Thus this beta function sees the value of num as the value before the next invocation of alpha, so 1 is printed later. If you also add print(proc) inside beta, you'll see that proc is equal to the gamma function which was first passed to alpha.

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

1 Comment

See also programiz.com/python-programming/closure for more information.

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.