Find Largest of Two Numbers in Python
Choose the larger of two Python numbers without forgetting equal inputs. A beginner three-branch walkthrough explains comparisons and the 12.0 output format.
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")
Sample Output
Largest number is: 12.0
The first response is larger, so its float value 12.0 is printed.
In this one
- Compare two numeric values
- Handle equality explicitly
- Follow first-match branching
How it works
- 1
Convert both responses with float.
- 2
Test a > b, then test b > a only if needed.
- 3
Use else for equal values and print the selected message.
Edge cases
Equal inputs
Enter 12 twice.
Both greater-than tests fail, so the equality message runs.
Two negative values
Enter -5 and -2.
-2 is larger because it lies closer to zero on the number line.
What's going on
There are three answers, not two: a is bigger, b is bigger, or they match. The code gives each answer its own branch. Skip the equal case and equal inputs can print nothing, which looks like the program stalled.
float allows decimal responses. For 12 and 9, a > b is True, so the first message runs and the remaining branches are skipped. If that test fails, Python tries b > a. For ordinary finite inputs, failing both comparisons means equality.
max(a, b) would return the larger value with less code. This lesson writes the decisions out so you can see them. The displayed 12.0 is not a calculation mistake; it is how the converted float is printed.
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.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which branch handles equal finite inputs?
Pick an answer to check it.
Question 2
Why does 12 print as 12.0?
Pick an answer to check it.
Questions people ask
Which branch handles equal finite inputs?
else, because neither greater-than comparison is true.
Why does 12 print as 12.0?
float converted the input, so print displays a floating-point number.
Can max replace these comparisons?
Yes. max(a, b) returns a largest value, but it does not provide this separate equality message.