w3resource

Python Exercise: Find the Max of three numbers


1. Maximum of Three Numbers

Write a Python function to find the maximum of three numbers.

Sample Solution:

Python Code:

# Define a function that returns the maximum of two numbers
def max_of_two(x, y):
    # Check if x is greater than y
    if x > y:
        # If x is greater, return x
        return x
    # If y is greater or equal to x, return y
    return y

# Define a function that returns the maximum of three numbers
def max_of_three(x, y, z):
    # Call max_of_two function to find the maximum of y and z,
    # then compare it with x to find the overall maximum
    return max_of_two(x, max_of_two(y, z))

# Print the result of calling max_of_three function with arguments 3, 6, and -5
print(max_of_three(3, 6, -5)) 

Sample Output:

6  

Explanation:

In the exercise above the code defines two functions: "max_of_two()" which finds the maximum between two numbers, and "max_of_three()" which finds the maximum among three numbers by utilizing the "max_of_two()" function. In the final print statement, the maximum is found among the given numbers: 3, 6, and -5.

Pictorial presentation:

Python exercises: Find the Max of three numbers.

Flowchart:

Flowchart: Python exercises: Find the Max of three numbers.

For more Practice: Solve these Related Problems:

  • Write a Python function that takes three parameters and returns the largest using nested ternary operators.
  • Write a Python function that finds the maximum of three numbers without using the built-in max() function by using if-else statements.
  • Write a Python function that accepts three numbers in a list and uses recursion to determine the maximum value.
  • Write a Python function that sorts three numbers and returns the last element as the maximum, ensuring the original order is preserved.

Go to:


Previous: Python-Functions-Exercises Home.
Next: Write a Python function to sum all the numbers in a list.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.