Python Program to Find the Largest of Three Numbers
Beginner · Basics · CBSE class 11 practical list
This program finds the largest and the smallest of three numbers. It keeps a running answer and updates it whenever a bigger or smaller number turns up, the same idea used for longer lists.
Program
largest_of_three_numbers.py
a = 12 # or: a = int(input("Enter the first number: "))
b = 47 # or: b = int(input("Enter the second number: "))
c = 30 # or: c = int(input("Enter the third number: "))
largest = a
if b > largest:
largest = b
if c > largest:
largest = c
smallest = a
if b < smallest:
smallest = b
if c < smallest:
smallest = c
print("Numbers:", a, b, c)
print("Largest number:", largest)
print("Smallest number:", smallest)
Output
Numbers: 12 47 30 Largest number: 47 Smallest number: 12
How it works
- The program starts by assuming the first number,
a, is the largest and stores it inlargest. - It then compares
bandcwithlargestand replaces it whenever one of them is bigger. - The smallest number is found the same way, with
<instead of>. - Because each comparison updates one variable, the same approach works for any number of values.
Other ways to write it
Using if-elif with and
Using if-elif with and
a, b, c = 12, 47, 30
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("Largest of", a, b, c, "is", largest)
Output
Largest of 12 47 30 is 47
Each condition checks one number against both of the others, and >= makes sure equal numbers still give an answer.
Using max() and min()
Using max() and min()
a, b, c = 12, 47, 30
print("Largest number:", max(a, b, c))
print("Smallest number:", min(a, b, c))
Output
Largest number: 47 Smallest number: 12
max() and min() accept any number of values, so this is the shortest way to write it.
Try it yourself
Add a fourth number d and update the program so it still finds the largest and the smallest.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises