Python – Find Maximum of Two Numbers

Find Maximum of Two Numbers

There are many ways to find out the maximum of given two numbers. In this tutorial, we will learn three ways of finding out the maximum of two numbers.

1. Find Maximum using max() builtin function

To find the maximum of given two numbers in Python, call max() builtin function and pass the two numbers as arguments. max() returns the largest or the maximum of the given two numbers.

The syntax to find the maximum of two numbers: a, b using max() is

max(a, b)

In the following program, we take numeric values in two variables a and b, and find out the maximum of these two numbers using max().

Python Program

a = 7
b = 52
maximum = max(a, b)
print(f'Maximum of {a}, {b} is {maximum}')
Run Code Copy

Output

Maximum of 7, 52 is 52

2. Find Maximum Value using If Statement

In the following program, we will use simple If statement to find the maximum of given two numbers.

Python Program

a = 7
b = 52

maximum = a
if b > a :
    maximum = b

print(f'Maximum of {a}, {b} is {maximum}')
Run Code Copy

Output

Maximum of 7, 52 is 52

3. Writing our own Lambda Function to find Maximum Value

We can also write a lambda function to find the maximum of two numbers. We use Ternary Operator inside lambda function to choose the maximum value.

In the following program, we write a lambda function that can return the maximum of given two numbers.

Python Program

a = 7
b = 52
maximum = lambda a, b: a if a > b else b
print(f'Maximum of {a}, {b} is {maximum(a, b)}')
Run Code Copy

Output

Maximum of 7, 52 is 52

Related Tutorials

Code copied to clipboard successfully 👍