Given two numbers, the task is to find the smaller (minimum) number between them. For Example:
Input: a = 7, b = 3
Output: 3
Let's explore different methods to find the minimum of two numbers in Python.
Using min() Function
Python provides the built-in min() function, which compares multiple values and returns the smallest one.
a = 15
b = 9
print(min(a, b))
Output
9
Explanation: min() function compares a and b and returns the smaller value, which is 9.
Using Ternary Operator
The ternary operator allows us to write a conditional expression in a single line and return a value based on a condition.
a = 15
b = 9
res = a if a < b else b
print(res)
Output
9
Explanation: condition a < b is checked. Since it is false, the expression returns b, which is 9.
Using if-else Statement
We can use an if-else statement to compare the two numbers and print the smaller one.
a = 9
b = 15
if a < b:
print(a)
else:
print(b)
Output
9
Explanation: condition a < b evaluates to True, so a is printed. Therefore, the output is 9.