Python Program - Largest of Three Numbers
Python - Find Largest of Three Numbers
To find the largest of three numbers, we could write a compound condition to check if a number is greater than other two.
Examples
1. Find largest of three numbers using If statement
In this example, we shall use simple Python If statement to find the largest of three numbers.
We shall follow these steps to find the largest number of three.
- Read first number to a.
- Read second number to b.
- Read third number to c.
- If a is greater than b and a is greater than c, then a is the largest of the three numbers.
- If b is greater than a and b is greater than c, then b is the largest of the three numbers.
- If c is greater than a and c is greater than b, then c is the largest of the three numbers.
Python Program
a = 5
b = 4
c = 7
largest = 0
if a > b and a > c:
largest = a
if b > a and b > c:
largest = b
if c > a and c > b:
largest = c
print(largest, "is the largest of three numbers.")
Output
7 is the largest of three numbers.
2. Find largest of three numbers using if-elif
In our previous example, we have written conditions to find the largest. But, these conditions are independent of each other. And we have not taken advantage that if a is not greater than either of b or c, then there is no use to check if b is greater than a or c is greater than a.
So, using elif statement, we shall take advantage of the dependency of conditions.
Python Program
a = 22
b = 33
c = 11
largest = 0
if a > b and a > c :
largest = a
elif b > c :
largest = b
else :
largest = c
print(largest, "is the largest of three numbers.")
Output
33 is the largest of three numbers.
Summary
In this tutorial, we learned how to find the largest of three numbers using conditional statements.