Max of 3 numbers - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Max of 3 numbers (/thread-15518.html) |
Max of 3 numbers - MrGoat - Jan-20-2019 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 forthBut 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... RE: Max of 3 numbers - stullis - Jan-20-2019 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. RE: Max of 3 numbers - perfringo - Jan-20-2019 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)
|