Exaplain the below code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Exaplain the below code

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

13th Mar 2020, 11:29 AM
madhan mallisetty
madhan mallisetty - avatar
3 Answers
+ 5
Begin from end: Do_twice gets a func, x and y func =add X,y = 5,10 It returns add(add(5,10),add(5,10)) = add(15,15)=30 The prog demonstrates that a function can be a parameter like integer.
13th Mar 2020, 11:36 AM
Oma Falk
Oma Falk - avatar
+ 1
It's calling function inside function by passing function inside it. Let's begin from the last line and go from bottom to top. print(do_twice(add,a,b)) Here do_twice function will be called by paasing three values. First is func, which is function name, Second a and third b are values. Now in definition of do_twice, The function add is called by passing output of two more function calls. Let's understand the line- return func(func(x,y) , func(x,y)) here func() means to call add() function defined at top. first we are calling the function with values 5,10 twice and passing the result again in first and second parameter. It will look like - do_twice(add, 5, 10) func(func(5,10),func(5,10)) func(15,15) 30 So the output 30 will be printed. I hope you did not get confused here. 😅
13th Mar 2020, 11:39 AM
Sachin Artani
Sachin Artani - avatar
0
Function msg ( ) { do. While( 12.5*14.0) ; goString(x+y) ; } THIS IS C++ PROGRAM. SHARE WITH ALL YOUR FRIENDS.
16th Oct 2021, 1:24 PM
Shubham Bhatia
Shubham Bhatia - avatar