Practice: Temperature Conversion

Practice: Temperature Conversion

This exercise combines defining a function, parameters, arithmetic, and return.

The conversion from Fahrenheit to Celsius is:

celsius = (fahrenheit - 32) * 5 / 9

Exercise

  1. Define a function named to_celsius with one parameter, fahrenheit.
  2. It returns the temperature in Celsius, using the formula above.

Reference points to check against:

  • to_celsius(212) returns 100.0 — water boils
  • to_celsius(32) returns 0.0 — water freezes

Run your code to see the output, then press Submit.

Hints

  • Put the subtraction in parentheses; without them the multiplication happens first.
  • Return the result. Do not print inside the function.

Tests

import unittest


class TestToCelsius(unittest.TestCase):
    def test_boiling_point_212_f_is_100_c(self):
        self.assertAlmostEqual(to_celsius(212), 100.0)

    def test_freezing_point_32_f_is_0_c(self):
        self.assertAlmostEqual(to_celsius(32), 0.0)

    def test_body_temperature_98_6_f_is_37_c(self):
        self.assertAlmostEqual(to_celsius(98.6), 37.0)

    def test_negative_40_is_the_same_in_both(self):
        self.assertAlmostEqual(to_celsius(-40), -40.0)
def to_celsius(fahrenheit):
    return (fahrenheit - 32) * 5 / 9


print(to_celsius(212))
print(to_celsius(32))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.