What You'll Learn
- •Comparing two numeric values
- •Using if-elif-else chains
- •Handling the equality case explicitly
Python
# Program to find the largest of two numbers
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
if a > b:
print("Largest number is:", a)
elif b > a:
print("Largest number is:", b)
else:
print("Both numbers are equal")Output
Enter first number: 12 Enter second number: 9 Largest number is: 12.0
Find Largest of Two Numbers in Python
We compare two numbers using relational operators and conditional statements.
Relational Operators
>(greater than) - checks if left value is greater than right value<(less than) - checks if left value is less than right value==(equal to) - checks if two values are equal
Using if-elif-else
We use if-elif-else to handle all three cases:
a > b→ a is largerb > a→ b is larger- Else → they are equal
This is a foundational pattern for comparison-based problems.
Program Logic
pythonif a > b: print("Largest number is:", a) elif b > a: print("Largest number is:", b) else: print("Both numbers are equal")
Key Takeaways
1
Use
> operator to compare numbers2
if-elif-else handles multiple conditions3
Always handle the equality case
4
This pattern extends to comparing three or more numbers
Step-by-Step Breakdown
- 1Read two numbers from the user.
- 2Compare a and b using >.
- 3Print the larger number.
- 4If neither is greater, print that they are equal.