Write a function that averages three numbers.
average_of_three(a, b, c)
Return (a + b + c) / 3, rounded to 2 decimal places.
average_of_three(1, 2, 3) // → 2.0
average_of_three(10, 20, 30) // → 20.0
average_of_three(5, 5, 6) // → 5.33
def average_of_three(a, b, c):
return round((a + b + c) / 3, 2)
The parentheses around (a + b + c) matter for the same reason they did in Fahrenheit To Celsius: without them, Python's operator precedence would divide c by 3 first and then add a + b, which is a completely different (and wrong) computation.
/ in Python always performs true division and returns a float, so (1 + 2 + 3) / 3 gives 2.0, not 2 — that's why the average of three whole numbers can still come out with a decimal point. round(x, 2) then caps the result at two decimal places, which matters once the division doesn't divide evenly — (5 + 5 + 6) / 3 is 5.333333..., and round(..., 2) turns that into a clean 5.33.
def average_of_three(a, b, c):
return round((a + b + c) / 3, 2)
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.