Exercise

As a practical exercise, let's solve a simple, yet annoying, problem: converting the temperature from Celsius to Fahrenheit and back. Indeed, the formula is easy, but every time we need to do it in our head, it takes some time. The formulas are as follows:

T(°F) = T(°C) × 9/5 + 32

T(°C) = (T(°F) - 32) × 5/9

Let's calculate the Celsius equivalent of 100°F!

First, let's store the constants and our input as variables:

CONST = 32
RATIO = 5/9

T_f = 100

Now, let's do the conversion:

>>> T_c = (T_f - CONST) * RATIO
>>> T_c
37.77777777777778

Now, let's convert it back:

>>> T_f2 = (T_c / RATIO) + CONST
>>> T_f2
100.0

What is the simplest way to compute the following code for a different temperature? It seems that the easiest way is to change the initial value of the variables, and everything else should follow. Let's run the code for 70°F:

>>> T_f = 70
>>> T_c = (T_f - CONST) * RATIO
>>> T_c
21.11111111111111

Pretty neat! In the next chapter, we'll learn how to make this calculation even more convenient and easy to reuse by writing it as a function.

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

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