Find Largest of Two Numbers

Compare two numbers and print the larger one (or that they are equal).

PythonBeginner

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:

  1. a > b → a is larger
  2. b > a → b is larger
  3. Else → they are equal

This is a foundational pattern for comparison-based problems.

Program Logic

python
if 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 numbers
2
if-elif-else handles multiple conditions
3

Always handle the equality case

4

This pattern extends to comparing three or more numbers

Step-by-Step Breakdown

  1. 1Read two numbers from the user.
  2. 2Compare a and b using >.
  3. 3Print the larger number.
  4. 4If neither is greater, print that they are equal.