How are functions used as arguments in other functions? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How are functions used as arguments in other functions?

I'm working through the python course at the moment and have just come to the functions as objects section, specifically the functions being used as arguments in other functions and I can't work out what the code that has been provided means here is the SoloLearn example: def add(x, y): return x + y def do_twice(func, x, y): return funcfunc(x, y), func(x, y)) a = 5 b = 10 print(do_twice(add, a, b)) Now, i'm pretty sure there is an error in the example code with the presence of two parentheses for the return funcfunc(x, y), func(x, y)) line of code and as i'm quite new to this I have no idea what the example code is trying to demonstrate. Could anyone help me out please? thanks :)

11th Mar 2021, 10:19 PM
Archie
1 Answer
+ 2
You pass a reference to a function when you pass a function name as argument . do_twice(add, a, b) calls def do_twice(func, x, y) : // where func is a reference to add , and now calling func() inside it would make a call to add() function. return func(func(x, y), func(x, y)) //calls the innermost functions first. func(x, y) makes call to add() with arguments x and y which in turn returns their sum (15) , similar for second func(x, y) . Now we are left with , return func(15, 15) which again makes call to add and returns 30 this time.
11th Mar 2021, 10:32 PM
Abhay
Abhay - avatar