Find Maximum of two numbers in Python
Last Updated :
29 Nov, 2024
Improve
In this article, we will explore various methods to find maximum of two numbers in Python. The simplest way to find maximum of two numbers in Python is by using built-in max() function.
a = 7
b = 3
print(max(a, b))
Output
7
Explanation:
- max() function compares the two numbers a and b.
- So, it returns 7 as the larger value
Let’s explore other different method to find maximum of two numbers:
Table of Content
Using Conditional Statements
Another way to find the maximum of two numbers is by using conditional statements like if and else. This approach gives us more control over the logic and is useful when we need to implement custom rules.
a = 5
b = 10
if a > b:
print(a)
else:
print(b)
Output
10
Explanation:
- The if statement checks whether a is greater than b.
- If the condition is true then it prints a otherwise it prints b.
- Since b is greater so, it prints 10.
Using Ternary Operator
Python also supports a shorthand version of conditional statements known as the ternary operator. It allows us to write concise conditional expressions on a single line.
a = 7
b = 2
res = a if a > b else b
print(res)
Output
7
Explanation:
- The ternary operator evaluates the condition a > b.
- If true then it returns a, otherwise it returns b.
- Here, since a is greater so the result is 7.