Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Program output with nested function and function parameter

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading