In Chapter 2, First Steps in Coding – Variables and Data Types, we've performed a simple exercise by converting temperature from Fahrenheit to Celsius, and back. The approach was similar to how we'd use a calculator, except that we were able to store parameters beforehand, and then rerun the calculations for the new inputs. At this point, you can probably see that this is a great case for a separate function. So, let's refactor our code into a pair of functions:
def fahrenheit_to_celsius(temp):
CONST, RATIO = 32, 5/9
return (temp – CONST) * RATIO
def celsius_to_fahrenheit(temp):
CONST, RATIO = 32, 5/9
return (temp/RATIO) + CONST
Let's now test these function as follows:
>>> fahrenheit_to_celsius(100)
37.77777777777778
>>> celsius_to_fahrenheit(37.77777777777778)
100.0
>>>...