Largest of Three Numbers in Python
Problem statement
Given three numbers, print the largest. Equal values may appear — any of the tied largest values is a correct answer.Approach 1: simple loop
Compare with an if/elif ladder. Each condition asks "is this number at least as large as both others?" and the first true branch wins.
a, b, c = 12, 45, 23
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print(largest)
# Output: 45Note the >=: with ties like 7, 7, 3, the first branch still fires and the answer is correct.
Approach 2: reusable function
Keep a running champion: start with the first number, replace it whenever a later number beats it. This shape scales to ten numbers without changing its logic.
def largest_of(numbers):
best = numbers[0]
for n in numbers[1:]:
if n > best:
best = n
return best
print(largest_of([12, 45, 23])) # 45
print(largest_of([5, 5, 5])) # 5
print(largest_of([-2, -9, -4])) # -2Only two ideas: remember the best so far, and update on a strict win. The negative-numbers case works because every comparison is relative.
Approach 3: Pythonic alternative
Python has a built-in for "largest": max(). It accepts any number of arguments, or a single list, and even a key function for custom ordering.
a, b, c = 12, 45, 23 print(max(a, b, c)) # 45 print(max([12, 45, 23])) # 45 — same thing via a list
For exams, write the ladder; for code you will keep, max() says exactly what it means.
Dry run
Trace the champion version with [12, 45, 23]. Start: best = 12. Compare 45 > 12 → yes, best = 45. Compare 23 > 45 → no, best stays 45. Answer: 45 — two comparisons, exactly what is needed for three numbers. For the ladder version, the first test 12 >= 45 fails immediately, the second 45 >= 12 and 45 >= 23 passes, and b is printed.
Common errors
- Writing
a > b or a > c— "or" makes the condition far too easy to satisfy; a number larger than only one of the others slips through. Useand. - Using
=in the comparison instead of==/>=. - Assuming the numbers are positive — starting "largest" at 0 breaks on all-negative input; start with the first number instead.
- Forgetting ties: strict
>everywhere can leave the answer unset in the ladder version. - Printing all three branches' results — only one comparison chain should win.
Practice on PyDebug
Turn the idea into a debugging habit with these free browser exercises: