0

I don't understand this code. Somebody help me!

Function as a object.

16th Sep 2018, 2:28 PM
Kushan Sharma
Kushan Sharma - avatar
8 ответов
+ 3
You have to read the code from inside out: In the inner parentheses, the function add is called two times for the values 5 and 10. What's the result of the two calls, what is there after the return? 15+15. Now for these values, add is called again - the result is 30. And that is finally returned by do_twice and printed.
16th Sep 2018, 3:01 PM
HonFu
HonFu - avatar
+ 4
That's better! There are two functions in this code. add(x,y) takes two variables (x and y) as parameters and will just return their sum. So, for a = 5 and b = 10, add(a, b) will return 15. The function do_twice is a bit tricky. It takes a function name (func) and two variables (x and y) as parameters. Here, we call the function with the parameters add (that's our function), a and b (these are our variables). If you look at the return statement of do_twice, it looks liks this: func(func(x, y), func(x, y)). If you replace "func" with the function name that the function receives as a parameter (=add) and x and y with the variables it receives as parameters (=a and b), the return statement actually looks like this: return add(add(a, b), add(a, b)) or, if you insert the values of a and b: return add(add(5, 10), add(5, 10)) The next step will be that the expressions within the parentheses are calculated. Both "add(5, 10)" will be replaced by the return value (15): return add(15, 15) Now, add() is called again and it adds 15 and 15. Again, add(15, 15) is replaced by the return value: return 30 There's nothing more to calculate and the function do_twice() will return the value 30.
16th Sep 2018, 3:01 PM
Anna
Anna - avatar
+ 3
To be fair, that's not really a code. It's just two words, function and argument
16th Sep 2018, 2:37 PM
Anna
Anna - avatar
+ 2
You're welcome. Let's say thank you to HonFu too
16th Sep 2018, 3:34 PM
Anna
Anna - avatar
+ 2
thank you HonFu
16th Sep 2018, 4:01 PM
Kushan Sharma
Kushan Sharma - avatar
+ 1
Whoops. :)
16th Sep 2018, 3:02 PM
HonFu
HonFu - avatar
+ 1
thank you Anna
16th Sep 2018, 3:31 PM
Kushan Sharma
Kushan Sharma - avatar
0
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))
16th Sep 2018, 2:42 PM
Kushan Sharma
Kushan Sharma - avatar