This elementary activity is intended to check and consolidate your understanding of very basic python language features. It is modeled after a similar activity in [HPL] and involves a simple temperature conversion formula. You may have seen kitchen cheat sheets (or have one yourself) like the following:
Fahrenheit | Celsius | |
---|---|---|
cool oven | 200 F | 90 C |
very slow oven | 250 F | 120 C |
slow oven | 300-325 F | 150-160 C |
moderately slow oven | 325-350 F | 160-180 C |
moderate oven | 350-375 F | 180-190 C |
moderately hot oven | 375-400 F | 190-200 C |
hot oven | 400-450 F | 200-230 C |
very hot oven | 450-500 F | 230-260 C |
This is modeled after a conversion table at the website Cooking Conversions for Old Time Recipes, which many found particularly useful for translating old recipes from Europe. Of course, the "old continent" has already moved on to the newer, more rational, metric system, so all European recipes, old and new, are bound to have temperatures in Celsius (C). Even if recipes don't peak your interest, do know that every scientist must learn to work with the metric system.
Celsius values can be converted to the Fahrenheit system by the formula
$$
F = \frac 9 5 C + 32.
$$
The task in this activity is to print a table of F and C values per this formula. While accomplishing this task, you will recall basic python language features, like while
loop, for
loop, range
, print
, list and tuples, zip
, and list comprehension.
while
loop¶We start by making a table of F and C values, starting from 0 C to 250 C, using the while
loop.
print('F C')
C = 0
while C <= 250:
F = 9 * C / 5 + 32
print(F, C)
C += 10
This cell shows how to add, multiply, assign, increment, print, and run a while loop. Such basic language features are introduced very well in the prerequisite reading for this lecture, the official python tutorial's section titled "An informal introduction to Python." (Note that all pointers to prerequisite reading materials are listed together just after the table of contents in the beginning.)
Examining the output above, we note that it is not perfectly aligned like a printed table. Here is how we can use print
's features to format or align them to our tastes.
Formatting options like %10.3f
can be used for alignment. It's easy to describe this by an example:
%10.3f: print 3 decimals, field width 10
%9.2e: print 2 decimals, field width 9, scientific notation
Type help(print)
to recall these and other options. Below, we use a fixed width of 4 to format F and C values.
print(' F C')
C = 0
while C <= 250:
F = 9 * C / 5 + 32
print('%4.0f %4.0f' % (F, C))
C += 10
for
loop¶In addition to the while
loop construct, python also has a for
loop, which is often safer from an accidental bug sending the system into an infinite loop. Also recall the very useful range
construct. The loop statement
for i in range(4):
runs over i=0,1,2,3
implicitly using range
's default starting value 0
and the default stepping value 1
. For our temperature conversion task, we step by 10 degrees instead of the default value of 1:
print(' F C')
for C in range(0, 250, 10):
F = 9 * C / 5 + 32
print('%4.0f %4.0f' % (F, C))
As you can see from the above values, for a 10 degree increase in the C column, we see a corresponding 18 degree increase in the F column. Due to the these different rates of increase, we should see the values coincide by going to lower C values. Focusing on lower C values, let us run the for
loop again:
print(' F C')
for C in range(-50, 50, 5):
F = 9 * C / 5 + 32
print('%4.0f %4.0f' % (F, C))
As you see from the output above, at $-40$ degrees, the Fahrenheit scale and the Celsius scale coincide. If you have lived in Minnesota, you probably know how $-40$ feels like, and you likely already know the fact we just discovered above (it's common for Minnesotans to throw around this tidbit while commiserating in the cold).
If we want to use the above-printed tables later, we would have to run a loop again. Our conversion problem is so small that there is no cost to run as many loops as we like, but in many practical problems, loops contains expensive computations. So one often wants to store the quantities computed in the loop in order to reuse them later. Lists are good constructs for this.
First we should note that python has lists and also tuples. Only the former can be modified after creation. Here is an example of a list:
Cs = [0, 10] # create list using []
Cs.append(20) # modify by appending an entry
Cs
And here is an example of a tuple:
Cs = (0, 10) # create a tuple using ()
You access a tuple element just like a list element, so Cs[0]
will give the first element whether or not Cs
is a list or a tuple. But the statement Cs[0] = -10
that changes an element of the container will work only if Cs
is a list. We say that a list is mutable, while a tuple is immutable. Tuples are generally faster than lists, but lists are more flexible than tuples.
Here is an example of how to store the computed C and F values within a loop into lists.
Cs = [] # empty list
Fs = []
for C in range(0, 250, 25):
Cs.append(C)
Fs.append(9 * C / 5 + 32)
The lists Cs
and Fs
can be accessed later:
print(Cs)
print(Fs)
This is not as pretty an output as before. But we can easily run a loop and print the stored values in any format we like. This is a good opportunity to show off a pythonic feature zip
that allows you to traverse two lists simultaneously:
print(' F C')
for C, F in zip(Cs, Fs):
print('%4.0f %4.0f' % (F, C))
An alternate and very interesting way to make lists in python is by the list comprehension feature.
Codes with list comprehension read almost like English. Let's illustrate this by creating the list of F values from the existing list Cs
of C values.
Instead of making Fs
in a loop as above, in a list comprehension, we just say that each value of the list Fs
is obtained applying a formula for each C
in a list Cs
:
Fs = [9 * C / 5 + 32 for C in Cs]
Note how this makes for compact code without sacrificing readability: constructs like this are why your hear so much praise for python's expressiveness. For mathematicians, the list comprehension syntax is also reminiscent of the set notation in mathematics: the set (list) $\mathsf{Fs}$ is described in mathematical notation by
$$
\mathsf{Fs} = \left\{ \frac 9 5 C + 32: \; C \in \mathsf{Cs}\right\}.
$$
Note how similar it is to the list comprehension code. (Feel free to check that the Fs
computed by the above one-liner is the same as the Fs
we computed previously within a loop.)
Author: Jay Gopalakrishnan
License: ©2020. CC-BY-SA
$\ll$Table of Contents