I'm currently learning Python and following a tutorial and made it to decorators. But before diving there, i want to get a good grasp of how inner function works and I came across this piece of code.
def max(a, b, c):
def max2(x, y):
return x if x >= y else y
return max2(a, max2(b, c))
main_max = max(15, 5, 10)
print(main_max)
Now, I'm trying to understand the logic behind it, but I can't seem to understand the sequence of passing the arguments. I ran it on debug mode and did the lines step-by-step and what I noticed was x is being assigned the value of b and y is being assigned the value of c. Why is that?
Is it because the second argument which is max2(b, c) is being evaluated first before evaluating max2(a, max2(b, c)) ?
Max takes three arguments. Max2 takes two arguments. The only relevant line of code is
return max2(a, max2(b, c))
We know that a is a. In order to continue the computation we need to resolve (using max2) the greater of b or c. In other words, max2(15, max2(5, 10)) can be thought of like
t = max2(5, 10) # (5 ? 10) = 10
return max2(15, t) # (15 ? 10) = 15
The only other thing to realize is that the scope of max2 is being limited to within max.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With