Reputation: 3
Could someone help explain what's going on here? I don't understand what is going on in the third part, and why the result is 9. Thank you!
>>> def square(x):
return x ** 2
>>> def f(x):
return x * x
>>> def try_f(f):
return f(3)
>>> try_f(square)
9
Upvotes: 0
Views: 541
Reputation: 22021
you call square function by parameter passing from try_f function and pass 3 as argument to it. You can add print to observe which function is called.
Defining f function doesn't take affect try_f behavour
Upvotes: 0
Reputation: 7150
When calling try_f(square)
you are passing the square
function to try_f
.
Inside try_f
you named the first argument f
: it will have nothing to do with the f()
function defined below. This is now a local variable to the current scope of try_f
.
As a better example, take this:
def square(x):
return x * x
def double(x):
return x * 2
def try_f(func):
return func(4)
>>> try_f(square)
16
>>> try_f(double)
8
Upvotes: 1
Reputation: 2266
The third function has a function as a parameter so when called it runs the parameter-function with a 3 as a paramater.
try_f(f=square) resolves as square(x=3) which resolves as x*x= 3*3 = 9
Upvotes: 0