0

Python - function in a function

Hello everyone, I‘m stuck at lesson 3/6/3 cause I do not get the idea how a function in a function works. This is the code of the lesson I am talking about. 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)) What I don't understand the most is the statement part of the do_twice function. Is there another example to understand the idea behind it? I‘ve read through most of the comments but still don‘t get it.

16th May 2018, 5:11 PM
Nicola
Nicola - avatar
3 odpowiedzi
+ 1
do_twice just just gets a function as an argument and two arguments more. Suppose you have some binary operators, where you get two inputs and return an output(like add, subtract or divide) and you want to make a function that takes a binary operator and two inputs, and returns the output of the operator when input those two values(like eval_op), like so: def add(a,b): return a+b def sub(a,b): return a-b def eval_op(op, first, second): return op(first, second) eval_op(add,1,5) #returns 6 eval_op(sub,1,5) #returns -4
16th May 2018, 5:30 PM
Bebida Roja
Bebida Roja - avatar
+ 1
It’s quite simple. do_twice takes 3arguments: function, x and y. Look inside return of do_twice. func(x, y) evaluates to add(x, y). So the all difficulty is to understand it as add(add(x, y), add(x, y)) what evaluates to add(15, 15)
16th May 2018, 5:40 PM
Eterxoz
Eterxoz - avatar
0
The harder I try less I understand. I'm exhausted of this for today. Will take a fresh look tomorrow. Thanks anyway
16th May 2018, 6:57 PM
Nicola
Nicola - avatar