0

Want to know something about functions in python.

Why is it written (func,x,y) in the do_twice function. I mean why is func there instead of only x,y. Also add,a,b is there on the last line. Why not only a,b. What is the cause of writing add or func here. 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))

20th Mar 2019, 9:55 AM
Sagnik Majumder2
Sagnik Majumder2 - avatar
1 Resposta
+ 7
If you look at the last line, you'll see that the name of the function "add" is passed as a parameter name to the function call do_twice(). Then the function "add" is called from within "do_twice()" by calling func(). Check this to understand the concept better: def say_hello(): print('Hello') def execute_function(func): print(func) # print function name func() # execute function execute_function(say_hello) #output: <function say_hello at 0x7f3c8e726400> Hello ~~~~~~ Calling a function with a parameter: def print_text(text): print(text) def execute_function(func, param): func(param) # execute function "func" with parameter "param" execute_function(print_text, 'Yay') #output: Yay #The last function call is equivalent to: print_text('Yay') #output: Yay
20th Mar 2019, 10:22 AM
Anna
Anna - avatar