In this article, we will write a Python program to find the largest of three numbers using nested if else
statements. The program takes three numbers from the user as input, finds the largest among them and prints it on the output screen.
Sample Example:
Input: Enter first number: 20 Enter second number: 10 Enter third number: 30 Output: The largest number is: 30
To find out the largest of three numbers, there are two approaches that we generally use: First, using simple if…else statements and second using nested if…else statements.
Let’s say we have three numbers a
, b
& c
. To find out the largest of a
, b
& c
using the nested if...else
, we can use the following algorithm:
- Check if
a
is greater thanb
:- If yes, either
a
orc
is the largest. - Check, if the
a
is also greater thanc
, if yes,a
is the largest. - If not, the
c
is the largest.
- If yes, either
- If
a
is not greater thanb
, this means:- Either
b
orc
is the largest. - Check if
b
is also greater thanc
, if yes,b
is the largest. - If not,
c
is the largest.
- Either
Here is the implementation of the above algorithm in Python:
# Take the numbers from the user a = int(input('Enter first number: ')) b = int(input('Enter second number: ')) c = int(input('Enter third number: ')) # Find the largest among a, b & c if a > b: if a > c: largest = a else: largest = c else: if b > c: largest = b else: largest = c # Print the largest number print("The largest number is: ", largest)
Output:
Enter first number: 20 Enter second number: 100 Enter third number: 50 The largest number is: 100 Enter first number: -20 Enter second number: -10 Enter third number: -50 The largest number is: -10
This approach works for all positive and negative numbers including zero.