Someone please can explain me how this little tiny program works? Especially the first 2 lines of code that lead to the result. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Someone please can explain me how this little tiny program works? Especially the first 2 lines of code that lead to the result.

def apply_twice(func, arg): #This return func(func(arg)) #This def add_five(x): return x + 5 print(apply_twice(add_five, 10)) >>> 20 #To this

26th Jun 2021, 10:09 PM
Robert S. Soto
Robert S. Soto - avatar
2 Answers
+ 2
the code print the result of apply_twice function, called with the add_fivd function as first argument and 10 as second argument... so, apply_twice receive add_five function in func argument variable and 10 in arg argument variable, and return return value of func(func(arg)) wich is equivalent to add_five(add_five(10))... first is applied inner add_five(10) wich return 15, then outer add_five(15) wich return 20... so apply_twice return 20, and 20 is printed ^^
26th Jun 2021, 10:54 PM
visph
visph - avatar
+ 1
go through everything one step at a time. apply_twice(add_five, 10) in apply_twice(), it takes a function and an argument as parameters. Inside the apply_twice() function, it returns a call to the function given, with the parameters being: func=the same function given AND arg=an argument for the function given that looks like: apply_twice(add_five, 10) breaks down to (inside the function): add_five(add_five(10)) which is: add_five(15) and finally: 20
26th Jun 2021, 10:59 PM
Slick
Slick - avatar