Write a function that converts a temperature from Fahrenheit to Celsius.
fahrenheit_to_celsius(f)
Use the formula (f - 32) * 5 / 9, and round the result to 1 decimal place with round(x, 1).
The output should be a float rounded to 1 decimal place.
fahrenheit_to_celsius(32) // → 0.0
fahrenheit_to_celsius(212) // → 100.0
fahrenheit_to_celsius(98.6) // → 37.0
This is a direct formula translation, the exercise requires you to translate (f - 32) × 5⁄9 from math notation into Python, and getting the parentheses right.
A common mistake is writing f - 32 * 5 / 9 without the parentheses. Python's operator precedence would multiply 32 * 5 before subtracting, giving a completely different (wrong) number. Parentheses around (f - 32) makes sure the subtraction happens first, exactly as the formula intends.
round() is a built-in Python function that rounds a number to a specified number of decimal places. The first argument is the number to round, and the second argument is the number of decimal places to round to.
round(x, 1) rounds x to 1 decimal place and returns a float, that's why each expected output in the tests has exactly one digit after the decimal point, even when the math works out to a whole number (0.0, not 0).
Give it a go and try to implement the function!
def fahrenheit_to_celsius(f):
return round((f - 32) * 5 / 9, 1)
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.