I am studying the properties of functions in Python and I came across an exercise that asks to:
Write a function which returns de power of a number. Conditions: The function may only take 1 argument and must use another function to return the value of the power of a given number.
The code that solves this exercise is:
def power(x):
return lambda y: y**x
For example, if we would like to know the value of the power: 2^3, we would call the function like this: power(3)(2)
Here is what I would like to know:
Is there any way to write a function that, when called, has a similar structure: function()()().
In other words, is it possible to write a function, that requires three or more parentheses ()()() when called?
If it is possible, could you please give me an example code of that function and briefly explain it?
Also:
def power(x):
def power_extra(y):
return y
def power_another(z):
return z
return power_extra and power_another
Possible?
Sure you can:
When you call this function with argument 2 (
power_times(2)), it returns a lambda function that works likelambda x: lambda y: 2 * y ** x(that is, like your original function, only with an extra “times 2”).You can stack as many
lambdas on top of each other as you like:Indeed, it might be even clearer if you skipped using
defat all, and just wrote:Or, alternatively, you could skip using
lambdaever and just use them as nested functions: