Functions as objects | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Functions as objects

Hey! In the tutorial there is this example: ----------------------------------------------------------------- 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)) -------------------------------------------------------------------- which returns 15+15=30, but if i manipulate to this: --------------------------------------------------------------- def add(x, y): return 2*x + y def do_twice(func, x, y): return func(func(x, y), func(x, y)) a = 3 b = 1000 print(do_twice(add, a, b)) -------------------------------------------------------------- it returns 3018 which is 3 * 1006, but why is it not 2012 ? thanks a lot! :)

20th Jun 2017, 9:59 AM
SackRatteY
1 Answer
+ 5
The do_twice(add,a,b) call will return the value returned by add(add(a,b),add(a,b)) (with parameters values transmitted)... So, it return add(2*a+b,2*a+b) value, wich is: 2*(2*a+b)+(2*a+b) == 2*(2*3+1000)+(2*3+1000) == 2*(1006)+(1006) == 2012+1006 == 3018 ^^
20th Jun 2017, 11:35 AM
visph
visph - avatar