Program to Find the Greatest of Three Numbers in Python
Finding the Greatest of Three Numbers
Given three integer inputs num1, num2, and num3, the objective is to determine which number is the greatest using Python programming.
We will explore different methods to achieve this.
Method 1: Using if-else Statement
We use an if-else statement to compare three numbers and determine the greatest one.
num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) num3 = int(input("Enter third number: ")) if num1 >= num2 and num1 >= num3: print(f"{num1} is the greatest number") elif num2 >= num1 and num2 >= num3: print(f"{num2} is the greatest number") else: print(f"{num3} is the greatest number")
Output:
Enter three numbers: 5 10 7 10 is the greatest number
Method 2: Using Ternary Operator
We use the ternary operator to find the greatest number in a single line.
num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) num3 = int(input("Enter third number: ")) greatest = num1 if (num1 > num2 and num1 > num3) else (num2 if num2 > num3 else num3) print(f"{greatest} is the greatest number")
Output:
Enter three numbers: 7 3 9 9 is the greatest number
Method 3: Using Function
We create a function to compare three numbers and return the greatest one.
def find_greatest(a, b, c): return max(a, b, c) num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) num3 = int(input("Enter third number: ")) print(f"{find_greatest(num1, num2, num3)} is the greatest number")
Output:
Enter three numbers: 4 9 2 9 is the greatest number