Home > Blockchain >  I have a simple question about the logic behind this Python code
I have a simple question about the logic behind this Python code

Time:05-24

I'm a beginner in Python, and I'm stuck in a function code.

def max_of_two( x, y ):
    if x > y:
        return x
    return y
def max_of_three( x, y, z ):
    return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(30, 25, 50))

Can someone explain to me the logic behind putting the first function (max_of_two()) inside the parameters of the second function (max_of_three())? I've seen a function inside a function code, and that's not a problem, but I've never seen a function inside the parameters of another function... I'm very confused. I know what the code does, it basically shows the greater number. The first function I understood perfectly, but the second one confused me...

CodePudding user response:

x = 1
y = 2
z = 3

max_of_two( y, z )
> 3

max_of_two( x, max_of_two( y, z ) )
# is the same as
max_of_two( x, z )
# is the same as
max_of_two( x, 3 )

The result of the inner function is used as a parameter for the outer function because the inner function is evaluated first.

CodePudding user response:

This is not putting a function inside parameters. First I recommend you understand parameter vs argument, here's a quote from "Parameter" vs "Argument" :

Old post, but another way of saying it: argument is the value/variable/reference being passed in, parameter is the receiving variable used w/in the function/block

def max_of_three( x, y, z ):
    return max_of_two( x, max_of_two( y, z ) )

For example, (x, y, z) are parameters of max_of_three, and (y, z) are arguments passed to max_of_two

—————————————————————————————————————————— Then you should understand function calls. max_of_two( y, z ) is an example of a function call, where you call the function max_of_two, by making a function call, you get the return value corresponding to your arguments.

In this case, when you write:

max_of_two( x, max_of_two( y, z ) )

you first get the return value corresponding to (y, z) from max_of_two, and the pass x and the return value above to another max_of_two function, then you return the new return value from max_of_three. This is equivalent to:

retval = max_of_two( y, z )
retval2 = max_of_two( x, retval )
return retval2

CodePudding user response:

It's like a nested if in other languages. You have three arguments to the second function. These are passed to the first function that verifies them in pairs. If you wanted to use a single function max_of_three(x, y, z) it should look like a succession of if statements with an intermediary variable.

def max_of_three(x,y,z):
    if x > y:
       temp = x
    else:
       temp = y
    if temp > z:
       result = temp
    else:
       result = z
    return result
  • Related