Input three numbers and display the largest and the smallest number
Expt. No.03
Page No.6
Largest and smallest of three numbers
Aim
To write a Python program that accepts three numbers and displays the largest and the smallest of them.
Concepts used
Algorithm
- Input three numbers a, b and c.
- Assume a is the largest; replace it with b or c if either is greater.
- Assume a is the smallest; replace it with b or c if either is smaller.
- Display the largest and the smallest number.
Program
# Display the largest and the smallest of three numbers a = int(input("Enter the first number : "))b = int(input("Enter the second number: "))c = int(input("Enter the third number : ")) largest = aif b > largest: largest = bif c > largest: largest = c smallest = aif b < smallest: smallest = bif c < smallest: smallest = c print("Largest number :", largest)print("Smallest number:", smallest)
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python largest_smallest_of_three.py
Enter the first number : 23
Enter the second number: 87
Enter the third number : 15
Largest number : 87
Smallest number: 15
✓ Printed by running this program, not typed by hand.
Result
For the numbers 23, 87 and 15 the program displayed 87 as the largest and 15 as the smallest number.
Viva voce: what the examiner may ask
01Why are separate if statements used instead of elif here?
Each comparison must be checked on its own; with elif, the check for c would be skipped whenever b was larger than a.
02How else can the largest of three numbers be found?
With nested if statements, with if a > b and a > c, or with the built-in max(a, b, c).
03What does int() do if the user types 4.5?
It raises a ValueError, because the text "4.5" is not a whole number.
Variations for the lab test
- Use
if-elif-elsewithandto find the largest number. - Also display the number that is neither the largest nor the smallest.
- Extend the program to four numbers.
! Common mistake Starting with
largest = 0 fails when all three numbers are negative: the program would wrongly print 0.