0

This link talks about Python nested functions.

They have this example:

def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))

When I run it, it multiplies 10 by 5 and prints out 50. How does it "run"

res = num1(10)

... if the num1() function is only given a single argument of 10? y is not defined when num1(10) is run. The print function only executes when it runs res(5), but how are you "stuffing" two values into x in the parent function?

I'm thinking there's a bigger picture thing I'm not understanding in relation to how the function and order is running.

Thanks for looking at this beginner question. I'm just trying to understand... baby steps.

2
  • Edit: Thanks guys! Very easy for a beginner to understand. Commented Jul 8, 2020 at 1:02
  • The key point to understand is that functions are just objects like any other, just like int, str, list, dict etc, they can be created inside a function, and returned from that function, and you can assign functions to whatever variables you want. Commented Jul 8, 2020 at 1:18

2 Answers 2

3

When you run res = num1(10) it assigns a function to res, but doesn't run it.

You can kind of think of it like this (not valid syntax, only for illustration):

res = def num2(y):
        return 10 * y

Then when you call res, it actually runs the function and does the multiplication.

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

Comments

2

You supply y when you do res(5); y isn't given a value when num1 is run.

num1 returns a function that will require y. y is supplied when that returned function is called.

This is a common technique to delay the need for supplying information to a function. If a function accepts two parameters but you only have one of the arguments handy, you can return a function that wraps a call to the function where the known parameter already passed. You're left with a function that accepts the remaining data when it becomes available.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.