2

Im trying to figure out ,how this code works without calling the function (num2)?

Example:

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

print(res(5))

Output: 50

3 Answers 3

4

It does call num2. That's what gets assigned to res, so res(5) calls it.

It might be slightly clearer if you rewrite num1 to use a lambda expression (which is possible due to the simple nature of the function being defined and returned):

def num1(x):
    return lambda y: x * y

res = num1(10)  # res is a function that multiplies its argument by 10
print(res(5))
Sign up to request clarification or add additional context in comments.

Comments

2

If you try to print res without giving any argument in it, you can see it behaves like a function shortly points a function address ;

def num1(x):
   def num2(y):
      return x * y
   return num2

res = num1(10)

print(res)
print(res(5))

Output;

<function num1.<locals>.num2 at 0x02DDBE38>
50

Comments

1

I commented this to explain the functions.

# Defined function named num1 taking input 'x'
def num1(x):
    # Function 'num2' defined inside 'num1' taking input 'y'
   def num2(y):
    # Second function returning num1 input * num2 input
      return x * y
    # First function returning num2 is returned first
   return num2
# this is a variable for inputting to the nested functions.
# res = num1(num2)
res = num1(10)
# This is initializing num1 as 5
print(res(5))


# But it would be way easier...
def nums(x,y):
    return x * y

print(nums(5,10))

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.