1

Im trying to figure out how this code prints 5 7 as output. Im unable to understand how this code actually executes.

Code:

def outer_function(x):
    def inner_increment(x):
        return x + 2
    y = inner_increment(x)
    print(x,y)
outer_function(5)

Output:

5 7
1
  • 1
    This question would be a little more interesting if inner_increment was defined as def inner_increment(): and using x from the scope of outer_function. As it stands, inner_increment is declaring it's own variable x which masks the parameter from outer_function, using none of the scope from outer_function. Because there is no dependency on the scope of outer_function, there is no reason that inner_increment could not just be defined as another top level function. Commented Sep 16, 2020 at 6:08

1 Answer 1

3

It's so simple. As you know statements run sequentially, so the followings will happen:

1- inner_increment will be defined

2- y = inner_increment(x) called, so it passes 5 to the innter_increment function and get 7 as a result putting in y variable.

3- finally it will print 5 and 7 in the output.

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

Comments

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.