+ 1
def add(x, y): return x + y def do_twice(func, x, y): return func(func(x, y), func(x, y)) a = 5 b = 10 print(do_twice(add, a, b)) anybody can explain what is the relevance of func in this code?
4 odpowiedzi
+ 4
func mean that you need to give to do_twice() function as parameter. in this case we send the function add () to te function do_twice() that use this function inside.
so do_twice(add, a, b) return add (add(a,b),add (a,b))
+ 2
func is just alias for add here.
func is in local scope of do_twice so outside it will not be accessed.
+ 1
please note that it could be any name, just like the rest of parameters:
do_twice(any_name, x, y):
return any_name(any_name(x, y), any_name(x, y))
works fine too.
0
There are two function definitions.
add is ordinary function, it returns the sum of its parameters.
do_twice is a function which has three arguments, one is a function and other two are ordinary numbers.
Your issue seems to be in passing function as a parameter to another function. So yes it can be done in Python