Python Forum

Full Version: Max of 3 numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, so I am supposed to write a function to find the maximum of 3 numbers. Initially I wanted to write a function that takes in 3 values and analyzes each case by case , like this :

def Max ( x, y, z)
    if x > y and y > z
       print x
    elif 
       x > y and y < z
       print z 
     .... so on and so forth 
But I realized that it is very tedious because there are quite a few possible cases.

So I looked at the solution and this is what it gave :

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(3, 6, -5))
But I don't understand how this code works. Isn't the code for max_of_two missing an else statement? Because it should return x if x > y and return y if x < y. I'm confused...
The function does not need an else statement. If x > y then the function returns x and exits; in all other cases (else), it reaches the end of the if statement, continues with the rest of the function, and returns y.
Function max_of_two compares two numbers and returns largest.

This statement:

max_of_two( x, max_of_two( y, z ))
First it evaluates and returns larger number from y and z max_of_two(y, z). Lets call it w. Then it evaluates and returns largest number from x and w (for better understanding just replace expression with its actual result, which will make second step: max_of_two(x, w)