Write a function that returns the largest of three numbers.
max_of_three(a, b, c)
max_of_three(1, 5, 3) // → 5
max_of_three(10, 2, 8) // → 10
max_of_three(4, 4, 4) // → 4
max_of_three(-1, -5, -2) // → -1
(Yes, Python's built-in max() does this in one call — but for this problem, practice it with if statements instead. You'll use the built-in freely from here on.)
This is the same "running best" pattern that shows up constantly in programming — start with a guess, then compare and update.
def max_of_three(a, b, c):
biggest = a
if b > biggest:
biggest = b
if c > biggest:
biggest = c
return biggest
Start by assuming a is the answer. Then check b: if it's bigger than what you've got so far, it becomes the new "biggest so far". Then check c the same way — importantly, it's compared against the updated biggest, which might already be b, not the original a.
Notice these are two separate if statements, not if/elif. That's deliberate: elif would mean "only check c if the b-check didn't match", but you always need to check c regardless of whether b won the previous comparison — imagine a=1, b=2, c=3: after comparing b, biggest is 2; you still need the second if to compare c=3 against it and update to 3.
def max_of_three(a, b, c):
biggest = a
if b > biggest:
biggest = b
if c > biggest:
biggest = c
return biggest
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.