Refactoring the temperature conversion

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

>>> fahrenheit_to_celsius(70)
21.11111111111111

Sweet! Everything seems to work as it should. Be aware that now, we don't need to reassign variables—all we need in order to get a new computation is to call this function with a new argument. While this particular function is rather simple, it is still better than having raw code around. For one, having a function reduces the cognitive complexity of the code – you don't need to remember the code that is stored inside, nor distinguish it from the other. In a broader sense, functions also add modularity – if needed, you can change the behavior and features of the function, without the need to change any code that uses this function. Last but not least, having your code wrapped in functions reduces the chance of human error – you can't mess with code you're not working with.

Now, let's talk about a special type of functions – anonymous functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.46.181