Python Program to Find Largest of Two Numbers
You can find the largest of two numbers in Python using
max(a, b) or by comparing with if a > b and printing the larger one.Examples
Inputa = 5, b = 10
Output10
Inputa = -3, b = -7
Output-3
Inputa = 4, b = 4
Output4
How to Think About It
To find the largest of two numbers, think about comparing them directly. If one number is bigger than the other, that number is the largest. If they are equal, either number is the largest.
Algorithm
1
Get the first number as input.2
Get the second number as input.3
Compare the two numbers using greater than operator.4
If the first number is greater, select it as the largest.5
Otherwise, select the second number as the largest.6
Print the largest number.Code
python
a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) if a > b: largest = a else: largest = b print("The largest number is", largest)
Output
Enter first number: 5
Enter second number: 10
The largest number is 10
Dry Run
Let's trace the example where a = 5 and b = 10 through the code
1
Input numbers
a = 5, b = 10
2
Compare a and b
Is 5 > 10? No
3
Select largest
Since 5 is not greater, largest = 10
4
Print result
Output: The largest number is 10
| Step | a | b | Condition (a > b) | Largest |
|---|---|---|---|---|
| 1 | 5 | 10 | False | 10 |
Why This Works
Step 1: Input numbers
We take two numbers from the user using input() and convert them to floats for general use.
Step 2: Compare numbers
Using if a > b, we check which number is bigger.
Step 3: Print largest
We store the larger number in largest and print it to show the result.
Alternative Approaches
Using max() function
python
a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) largest = max(a, b) print("The largest number is", largest)
This is shorter and uses Python's built-in function for clarity and simplicity.
Using ternary operator
python
a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) largest = a if a > b else b print("The largest number is", largest)
This method uses a compact one-line conditional expression for assignment.
Complexity: O(1) time, O(1) space
Time Complexity
The program compares two numbers once, so it runs in constant time, O(1).
Space Complexity
Only a few variables are used, so space complexity is constant, O(1).
Which Approach is Fastest?
All approaches run in constant time; using max() is most readable and concise.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If-else comparison | O(1) | O(1) | Clear logic and step-by-step understanding |
| max() function | O(1) | O(1) | Simplicity and readability |
| Ternary operator | O(1) | O(1) | Compact code style |
Use Python's built-in
max() function for a clean and simple way to find the largest number.Forgetting to convert input strings to numbers before comparing causes incorrect results or errors.