August 2019
Beginner
482 pages
12h 56m
English
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) * RATIOdef 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) ...