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
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))
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))