+ 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?

21st Aug 2016, 4:57 AM
anju
4 Answers
+ 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))
21st Aug 2016, 11:28 AM
‫Ido Tal
‫Ido Tal - avatar
+ 2
func is just alias for add here. func is in local scope of do_twice so outside it will not be accessed.
21st Aug 2016, 6:42 PM
Amit Gupta
Amit Gupta - avatar
+ 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.
30th Nov 2016, 5:04 PM
Eduardo Suarez
Eduardo Suarez - avatar
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
14th Dec 2016, 2:47 PM
Rishi Anand
Rishi Anand - avatar