0

Python functions

I couldn't fully understand how can a function can be used as an argument in python.

1st Jul 2020, 4:53 PM
MD Tahsin Rahman
MD Tahsin Rahman - avatar
3 Answers
+ 3
MD Tahsin Rahman I think you got stuck here. Right?? def add(x, y): return x + y # This creates a new function which will return it's sum. def do_twice(func, x, y): return func(func(x, y), func(x, y)) # This also creates a new function which will take 3 arguments i.e the function and the values of x and y. a = 5 b = 10 print(do_twice(add, a, b)) It will be more clear if you assume it like this. add(add(x,y),(add(x,y) It will first add these two values (5+10),(5+10) which is 15 and 15. and finally: add(15),(15) which is 30. In this way, functions can also be taken as arguments. Hope you understood 🙂 You can also take help from this thread:- https://www.sololearn.com/discuss/1670975/?ref=app
1st Jul 2020, 5:45 PM
Arctic Fox
Arctic Fox - avatar
+ 2
Functions can be used as values, which can be stored in lists and be assigned to variables. When ever you follow the value with parentheses () , the function will be called, like calling f in: some_list = [f] would be done by: some_list(...) When you want to use a function as value you need to remember omitting the parentheses (), otherwise the function will be called and you would get the return value instead.
1st Jul 2020, 5:53 PM
Seb TheS
Seb TheS - avatar
+ 1
#function as argument #function used as argument to other function def func(): print("Inside func") #callback function def test(callback): #print callback to verify the function obj print(callback) callback() #call test with func as argument test(func)
1st Jul 2020, 5:08 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar