Introduction
Finding the largest of three numbers is a common problem in programming. This tutorial will guide you through creating a Python program that compares three numbers and identifies the largest one.
Problem Statement
Create a Python program that:
- Takes three numbers as input.
- Compares the numbers to find the largest one.
- Displays the largest number.
Example:
- Input:
a = 10
,b = 25
,c = 20
- Output:
The largest number is 25
Solution Steps
- Take Input for Three Numbers: Use the
input()
function to get three numbers from the user. - Convert Input to Numeric Values: Convert the input strings to integers or floats using
int()
orfloat()
. - Compare the Numbers: Use conditional statements to compare the three numbers.
- Display the Result: Use the
print()
function to display the largest number.
Python Program
# Python Program to Find the Largest of Three Numbers
# Author: https://www.javaguides.net/
# Step 1: Take input for three numbers
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))
# Step 2: Compare the numbers to find the largest
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
# Step 3: Display the result
print(f"The largest number is {largest}")
Explanation
Step 1: Take Input for Three Numbers
- The
input()
function prompts the user to enter three numbers. Sinceinput()
returns a string, we convert it to a float usingfloat()
to handle decimal numbers.
Step 2: Compare the Numbers to Find the Largest
- The program uses conditional statements (
if
,elif
,else
) to compare the three numbers. It checks whethera
is greater than or equal to bothb
andc
. If true,a
is the largest. If not, it checks ifb
is greater than or equal to botha
andc
. If true,b
is the largest. Otherwise,c
is the largest.
Step 3: Display the Result
- The
print()
function is used to display the largest number. Thef-string
format is used to include the variable value directly within the string.
Output Example
Example:
Enter the first number: 10
Enter the second number: 25
Enter the third number: 20
The largest number is 25
Example:
Enter the first number: 7.5
Enter the second number: 3.2
Enter the third number: 9.8
The largest number is 9.8
Conclusion
This Python program demonstrates how to compare three numbers and determine the largest one using conditional statements. It’s a straightforward example that helps beginners understand basic comparison operations and decision-making in Python.