ByteBoard Notes Notes

Input two numbers and display the larger and the smaller number

Computer Science XI · Experiment 02 of 27 · Python

★ CBSE suggested11-CSPython programs
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

  1. Input two numbers a and b and convert them to float.
  2. If a is greater than b, a is larger and b is smaller.
  3. Else if b is greater than a, b is larger and a is smaller.
  4. 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

  1. Use int() instead of float() and test with whole numbers.
  2. Print the difference between the larger and the smaller number.
  3. Do the same task using the built-in max() and min() functions.
! Common mistake Comparing the inputs without converting them: "9" > "45" is True because strings are compared character by character.
Back to the 11-CS index