Passing values to functions ... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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.

8th Apr 2020, 2:48 PM
GeoK68
GeoK68 - avatar
1 Answer
+ 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)
8th Apr 2020, 5:11 PM
HonFu
HonFu - avatar