0

Why does it run the mult function twice to get a result of 16?

What is the output of this code? def test(func, arg): return func(func(arg)) def mult(x): return x * x print(test(mult, 2))

20th Nov 2019, 7:09 AM
Victor Perez Coriano
Victor Perez Coriano - avatar
1 ответ
+ 3
To understand this you need to imagine replacing parameter 'func' with 'mult' within the `test` function body. return func(func(arg)) ↓ return mult(mult(arg)) First we check the inner call for `mult` mult(arg) Is equivalent to mult(2) returns 2 * 2 => 4 Then we pass that result from inner call (4) to the outer call for `mult`, before we return it. mult(mult(arg)) Is equivalent to mult(4) # 4 is result from inner call mult(4) returns 4 * 4 => 16 And finally we return that result (16) to the `test` function caller. Hth, cmiiw
20th Nov 2019, 7:24 AM
Ipang