Python Program - Find Smallest of Three Numbers
Python - Find Smallest of Three Numbers
To find the smallest of three numbers, we could write a compound condition to check if a number is less than other two.
Examples
1. Find smallest of three numbers using If statement
In this example, we shall use simple Python If statement to find the smallest of three numbers.
We shall follow these steps to find the smallest number of three.
- Take three numbers in a, b, and c.
- If a is less than b and a is less than c, then a is the smallest of the three numbers.
- If b is less than a and b is less than c, then b is the smallest of the three numbers.
- If c is less than a and c is less than b, then c is the smallest of the three numbers.
Python Program
a = 14
b = 21
c = 67
smallest = 0
if a < b and a < c :
smallest = a
if b < a and b < c :
smallest = b
if c < a and c < b :
smallest = c
print(smallest, "is the smallest of three numbers.")
Output
67 is the smallest of three numbers.
2. Find smallest of three numbers using if-elif
In our previous example, we have written conditions to find the smallest. But, these conditions, we have written are independent of each other. And we have not taken advantage that if a is not less than either of b or c, then there is no use to check if b is less than a or c is less than a.
Also, if neither a nor b is the smallest, then it is evident that c is the smallest.
So, using elif statement, we shall take advantage of the dependency of conditions.
Python Program
a = 33
b = 66
c = 22
smallest = 0
if a < b and a < c :
smallest = a
elif b < c :
smallest = b
else :
smallest = c
print(smallest, "is the smallest of three numbers.")
Output
66 is the smallest of three numbers.
Summary
In this tutorial, we learned how to find the smallest of three numbers using conditional statements.