Input two numbers and display the larger and the smaller number
Expt. No.02
Page No.4
Larger and smaller of two numbers
Aim
To write a Python program that accepts two numbers and displays the larger and the smaller of them.
Concepts used
Algorithm
- Input two numbers a and b and convert them to float.
- If a is greater than b, a is larger and b is smaller.
- Else if b is greater than a, b is larger and a is smaller.
- Otherwise the two numbers are equal.
Program
# Display the larger and the smaller of two numbers a = float(input("Enter the first number : "))b = float(input("Enter the second number: "))if a > b: print("Larger number :", a) print("Smaller number:", b)elif b > a: print("Larger number :", b) print("Smaller number:", a)else: print("Both numbers are equal:", a)
A marked line continues the line above it. In your file, write it on the same line.
Output
Run 1
$ python larger_smaller_of_two.py
Enter the first number : 45
Enter the second number: 72
Larger number : 72.0
Smaller number: 45.0
Run 2
$ python larger_smaller_of_two.py
Enter the first number : 8.5
Enter the second number: 8.5
Both numbers are equal: 8.5
✓ Printed by running this program, not typed by hand.
Result
For 45 and 72 the program displayed 72.0 as the larger and 45.0 as the smaller number. For 8.5 and 8.5 it reported that both numbers are equal. The
.0 appears because the inputs were converted with float().Viva voce: what the examiner may ask
01Why is float() used around input()?
input() returns a string. Comparing strings compares them letter by letter, so "9" > "45" would be True. float() turns the text into a number.
02What is the difference between if-else and if-elif-else?
if-elif-else checks more than two cases; only the first true branch runs.
03Why is the else branch needed here?
When both numbers are equal neither a > b nor b > a is true, so without else nothing would be printed.
Variations for the lab test
- Use
int()instead offloat()and test with whole numbers. - Print the difference between the larger and the smaller number.
- Do the same task using the built-in
max()andmin()functions.
! Common mistake Comparing the inputs without converting them:
"9" > "45" is True because strings are compared character by character.