0
Passing values to functions ...
Can't remember where I came across this nugget, but I am having difficulty understanding how it works: def x (a = 0): def y (b = a): return a + b if a == 0: return y return y(a) print (x(2) + x()(3)) I understand what happens when x(2) is called, but I do not understand x()(3). My first thought was that it was two separate function calls ie x() then x(3). Some reverse engineering tells me that a is assigned 0 and b is assigned 3. How does this happen? A second question: what is the difference between return y and return y()? Do they both pass empty values? Thank you in advance.
1 Resposta
+ 1
In your outer function, there's another function definition.
Return y (without parentheses) means that this function itself is returned.
In Python, functions are like any other values and can be passed around. So they can also be return values.
x()(3) means that x is called (x()) and returns y.
And y, the return value which is a function, will now be called with the argument 3.
x()(3) -> y(3)