π Day 10/150 – Find the Largest of Two Numbers in Python
Welcome back to the 150 Days of Python series!
Today, we’ll solve a very common problem: finding the largest of two numbers.
This is a fundamental concept that helps you understand conditions, functions, and Python shortcuts.
π― Problem Statement
Write a Python program to find the largest of two numbers.
✅ Method 1 – Using if-else
The most basic and beginner-friendly approach.
a = 10 b = 25 if a > b: print("Largest number is:", a) else: print("Largest number is:", b)
π Explanation:
We simply compare both numbers and print the greater one.
✅ Method 2 – Taking User Input
Make your program interactive.
a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) if a > b: print("Largest number is:", a) else: print("Largest number is:", b)
π Why this matters:
Real-world programs always take input from users.
✅ Method 3 – Using a Function
Reusable and cleaner approach.
def find_largest(x, y): if x > y: return x else: return y print("Largest number:", find_largest(10, 25))
π Pro Tip:
Functions help you reuse logic anywhere in your code.
✅ Method 4 – Using Built-in max() Function
The easiest and most Pythonic way.
π Why use this?
Python already provides optimized built-in functions — use them!.
✅ Method 5 – Using Ternary Operator (One-Liner)
Short and elegant.
a = 10 b = 25 largest = a if a > b else b print("Largest number is:", largest)
π Best for:
Writing clean and compact code.
π§ Summary
| Method | Best For |
|---|---|
| if-else | Beginners |
| User Input | Real-world programs |
| Function | Reusability |
| max() | Clean & Pythonic |
| Ternary | Short one-liners |
π‘ Final Thoughts
There are multiple ways to solve the same problem in Python
and that’s what makes it powerful!
π Start simple → then move to cleaner and optimized approaches.


0 Comments:
Post a Comment