Find Largest of Two Numbers in Python
Three cases: a bigger, b bigger, or they match. The equal case is the one people skip.
BeginnerBasic Python ProgramsExample 6 of 25
find-largest-of-two-numbers.py
1# Program to find the largest of two numbers23a = float(input("Enter first number: "))4b = float(input("Enter second number: "))56if a > b:7 print("Largest number is:", a)8elif b > a:9 print("Largest number is:", b)10else:11 print("Both numbers are equal")
Output
Enter first number: 12 Enter second number: 9 Largest number is: 12.0
In this one
- you need three branches, not two
- equal inputs are the silent bug
What's going on
if a > b / elif b > a / else. The else is "they are equal". Skip it and equal inputs print nothing. Looks like a hang.
max(a, b) exists. This page is the if version so you see the three-way split.
Floats from input mean 12 prints as 12.0. Annoying, not wrong.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.