Minimum of two numbers in Python
Last Updated : 29 Nov, 2024
Improve
In this article, we will explore various methods to find minimum of two numbers in Python. The simplest way to find minimum of two numbers in Python is by using built-in min() function.
a = 7
b = 3
print(min(a, b))
Output
3
Explanation:
- min() function compares the two numbers a and b.
- So, it returns 3 as the smaller value
Let’s explore other different method to find minimum of two numbers:
Table of Content
Using Conditional Statements
Another way to find the minimum 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
5
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 5.
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
2
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 2.