Ways to find the maximum of three numbers in Python
In this tutorial, we will talk about the ways to find the maximum of three numbers in Python. There are multiple ways to get the largest element from three given numbers in Python. We will understand all those methods one by one.
Maximum of three numbers using if-elif-else
In this method, we are going to use a simple if-elif-else statement to achieve our goal which is to find the maximum of given three numbers. See the below example program to understand the concept.
a = 34 b = 45 c = 56 if a>=b and a>=c: print(a) elif b>=a and b>=c: print(b) else: print(c)
As you can see we have used if-elif-else with and operator to find the largest of a, b and c. The program prints the value of c that is 56.
Maximum of three numbers using max()
In this method, we will simply use a built-in function max() and pass all the three numbers separated with comma as shown in the code. The function returns the maximum of the passed values. Have a look at the code.
m = max(30, 45, 40) print(m)
The above program gives the output:
Using list and sort()
In this method, we will first create a list of the given numbers. Then we will sort the list using sort() method. Since the list is sorted in ascending order, the last element would be the largest. We can print this number passing -1 or 2 as the index in the list. Here, we have used -1. See the code and understand the concept.
a = 20 b = 40 c = 30 li = [20, 40, 30] li.sort() #printing last element print(li[-1])
And the output is: