Skip to Content
Learn Python by Building Data Science Applications
book

Learn Python by Building Data Science Applications

by Philipp Kats, David Katz
August 2019
Beginner
482 pages
12h 56m
English
Packt Publishing
Content preview from Learn Python by Building Data Science Applications

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) * 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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python for Data Science

Python for Data Science

Yuli Vasiliev
Introduction to Machine Learning with Python

Introduction to Machine Learning with Python

Andreas C. Müller, Sarah Guido

Publisher Resources

ISBN: 9781789535365Supplemental Content