+ 1

Can anyone explain how this code works?

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))

24th Aug 2021, 10:39 PM
Pankil Vishv Karma
Pankil Vishv Karma - avatar
4 Answers
+ 4
Which part do you not understand? Did you run it to see what it does? In case you haven't do so in the code playground.
25th Aug 2021, 12:56 AM
Simon Sauter
Simon Sauter - avatar
+ 2
Apparently you declared a higher order function, the first parameter takes a function which you declared before it, so what it does is to choose what kind of function it uses, you can even declare a sub(x, y) function to understand it further. However, this is very useful when you need to compare/calculate certain stuff of the same category. 👍
25th Aug 2021, 4:43 AM
Tim
Tim - avatar
+ 2
To build on what was just said, since you don't need to specify return type of a function, you can still see that they return integers whenever they're executed, the function was actually called 3 times, just for the record.
25th Aug 2021, 4:46 AM
Tim
Tim - avatar
0
Simon Sauter , how does return func(func(x,y), func(x,y)) takes the values and evaluate? I mean , from where did this func() came?
25th Aug 2021, 5:42 AM
Pankil Vishv Karma
Pankil Vishv Karma - avatar