Python Program to Find the Larger of Two Numbers
Beginner · Basics · CBSE class 11 practical list
This program compares two numbers and tells you which one is larger and which one is smaller. It also handles the case where both numbers are the same.
Program
larger_of_two_numbers.py
a = 45 # or: a = int(input("Enter the first number: "))
b = 72 # or: b = int(input("Enter the second number: "))
if a > b:
print("Larger number:", a)
print("Smaller number:", b)
elif b > a:
print("Larger number:", b)
print("Smaller number:", a)
else:
print("Both numbers are equal:", a)
Output
Larger number: 72 Smaller number: 45
How it works
- The two numbers are stored in
aandb, and the comments show how to read them withinput()instead. if a > bchecks whether the first number is bigger, and if so prints it as the larger one.elif b > acovers the opposite case, when the second number is bigger.- If neither number is bigger, they must be equal, so the
elsebranch says so.
Another way to write it
Using max() and min()
Using max() and min()
a = 45
b = 72
print("Larger number:", max(a, b))
print("Smaller number:", min(a, b))
Output
Larger number: 72 Smaller number: 45
The built-in max() and min() functions return the larger and the smaller value directly, which is the quickest way in real code.
Try it yourself
Set a and b to the same value and run the program to see the else branch.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises