Python Program to Find the Largest of Three Numbers using Nested If Else

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:

  1. Check if a is greater than b:
    • If yes, either a or c is the largest.
    • Check, if the a is also greater than c, if yes, a is the largest.
    • If not, the c is the largest.
  2. If a is not greater than b, this means:
    • Either b or c is the largest.
    • Check if b is also greater than c, if yes, b is the largest.
    • If not, c is the largest.

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.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts

Leave a Comment