ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 17.04.2021
Просмотров: 3725
Скачиваний: 3

Introduction to Python for Science, Release 0.9.23
and
del
from
not
while
as
elif
global
or
with
assert
else
if
pass
yield
break
except
import
class
exec
in
raise
continue
finally
is
return
def
for
lambda
try
In addition, you should not use function names, like
sin
,
cos
, and
sqrt
, defined in the
SciPy, NumPy, or any other library that you are using.
2.8 Script files and programs
Performing calculations in the IPython shell is handy if the calculations are short. But
calculations quickly become tedious when they are more than a few lines long. If you
discover you made a mistake at some early step, for example, you may have to go back
and retype all the steps subsequent to the error. Having code saved in a file means you
can just correct the error and rerun the code without having to retype it. Saving code can
also be useful if you want to reuse it later, perhaps with different inputs.
For these and many other reasons, we save code in computer files. We call the sequence
of commands stored in a file a
script
or a
program
or sometimes a
routine
. Programs
can become quite sophisticated and complex. Here we are only going to introduce the
simplest features of programming by writing a very simple script. Much later, we will
introduce some of the more advanced features of programming.
To write a script you need a text editor. In principle, any text editor will do, but it’s
more convenient to use an editor that was designed for the task. We are going to use the
Code Editor
in the Canopy window that appears when you launch the Canopy application
(see
). This editor, like most good programming editors, provides syntax
highlighting, which color codes key words, comments, and other features of the Python
syntax according to their function, and thus makes it easier to read the code and easier
to spot programming mistakes. The Canopy code editor also provides syntax checking,
much like a spell-checker in a word processing program, that identifies many coding
errors. This can greatly speed the coding process. Tab completion also works in the
Canopy Code Editor.
20
Chapter 2. Launching Python

Introduction to Python for Science, Release 0.9.23
2.8.1 Scripting Example 1
Let’s work through an example to see how scripting works. Suppose you are going on a
road trip and you would like to estimate how long the drive will take, how much gas you
will need, and the cost of the gas. It’s a simple calculation. As inputs, you will need the
distance of the trip, your average speed, the cost of gasoline, and the mileage of your car.
Writing a script to do these calculations is straightforward. First, launch Canopy and open
the code editor. You should see a tab with the word
untitled
at the top left of the code
editor pane (see
). If you don’t, go to the
File
menu and select
New
File
. Use the mouse to place your cursor at the top of the code editor pane. Enter the
following code and
save the code
in a file called
myTrip.py
in the
PyProgs
folder you
created earlier. This stores your script (or program) on your computer’s disk. The exact
name of the file is not important but the extension
.py
is essential. It tells the computer,
and more importantly Python, that this is a Python program.
# Calculates time, gallons of gas used, and cost of gasoline for a trip
distance
=
400.
# miles
mpg
=
30.
# car mileage
speed
=
60.
# average speed
costPerGallon
=
4.10
# price of gas
time
=
distance
/
speed
gallons
=
distance
/
mpg
cost
=
gallons
*
costPerGallon
The number (or hash) symbol
#
is the “comment” character in Python; anything on a line
following
#
is ignored when the code is executed. Judicious use of comments in your
code will make your code much easier to understand days, weeks, or months after the
time you wrote it. Use comments generously.
Now you are ready to run the code. Before doing so, you first need to use the IPython
console to move to the
PyProgs
directory where the file containing the code resides.
From the IPython console, use the
cd
command to move to the
PyProgs
directory. For
example, you might type
In [1]:
cd
~/
Documents
/
PyProgs
/
To
run
or
execute
a script, simply type
run
filename
, which in this case means type
run
myTrip.py
. When you run a script, Python simply executes the sequence of commands
in the order they appear.
In [2]:
run myTrip
.
py
Once you have run the script, you can see the values of the variables calculated in the
2.8. Script files and programs
21

Introduction to Python for Science, Release 0.9.23
script simply by typing the name of the variable. IPython responds with the value of that
variable.
In [3]:
time
Out[3]:
6.666666666666667
In [4]:
gallons
Out[4]:
13.333333333333334
In [5]:
cost
Out[5]:
54.666666666666664
You can change the number of digits IPython displays using the command
%precision
:
In [6]:
%
precision
2
Out[6]:
u’
%.2f
’
In [7]:
time
Out[7]:
6.67
In [8]:
gallons
Out[8]:
13.33
In [9]:
cost
Out[9]:
54.67
Typing
%precision
returns IPython to its default state;
%precision %e
causes
IPython to display numbers in exponential format (scientific notation).
Note about printing
If you want your script to return the value of a variable (that is, print the value of the
variable to your computer screen), use the
function. For example, at the end of
our script, if we include the code
(time)
(gallons)
(cost)
the script will return the values of the variables
time
,
gallons
, and
cost
that the
script calculated. We will discuss the
function in much greater detail, as well as
other methods for data output, in Chapter 4 on
22
Chapter 2. Launching Python

Introduction to Python for Science, Release 0.9.23
2.8.2 Scripting Example 2
Let’s try another problem. Suppose you want to find the distance between two Cartesian
coordinates
(
x
1
, y
1
, z
1
)
and
(
x
2
, y
2
, z
2
)
. The distance, of course, is given by the formula
∆
r
=
p
(
x
2
−
x
1
)
2
+ (
y
2
−
y
1
)
2
+ (
z
2
−
z
1
)
2
Now let’s write a script to do this calculation and save it in a file called
twoPointDistance.py
.
# Calculates the distance between two 3d Cartesian coordinates
import
numpy
as
np
x1, y1, z1
=
23.7
,
-
9.2
,
-
7.8
x2, y2, z2
= -
3.5
,
4.8
,
8.1
dr
=
np
.
sqrt( (x2
-
x1)
**
2
+
(y2
-
y1)
**
2
+
(z2
-
z1)
**
2
)
We have introduced extra spaces into some of the expressions to improve readability.
They are not necessary; where and whether you include them is largely a matter of taste.
There are two important differences between the code above and the commands we would
have written into the IPython console to execute the same set of commands. The first is
the statement on the second line
...
import
numpy
as
np
...
and the second is the “
np.
” in front of the
sqrt
function on the last line. If you leave out
the
import numpy as np
line and remove the
np.
in front of the
sqrt
function,
you will get the following error message
----> 7 dr = sqrt( (x2-x1)**2 + (y2-y1)**2 + (z2-z1)**2 )
NameError: name ’sqrt’ is not defined
The reason for the error is that the
sqrt
function is not a part of core Python. But it is a
part of the NumPy module discussed earlier. To make the NumPy library available to the
script, you need to add the statement
import numpy as np
. Then, when you call a
NumPy function, you need to write the function with the
np.
prefix. Failure to do either
will result in a error message. Now we can run the script.
In [10]:
run twoPointDistance
.
py
In [11]:
dr
Out[11]:
34.48
2.8. Script files and programs
23

Introduction to Python for Science, Release 0.9.23
The script works as expected.
The reason we do not have to import NumPy when working in the IPython shell is that
it is done automatically when the IPython shell is launched. Similarly, the package Mat-
PlotLib is also automatically loaded (imported) when IPython is launched. However,
when a script or program is executed, it is run on its own outside the IPython shell, even
if the command to run the script is executed from the IPython shell.
2.9 Importing Modules
We saw in Example 2 in the last section that we needed to import the NumPy module in or-
der to use the
sqrt
function. Indeed the NumPy library contains many useful functions,
some of which are listed in section
Python functions: a first look
. Whenever any NumPy
functions are used, the NumPy library must be loaded using an
import
statement.
There are a few ways to do this. The one we generally recommend is to use the
import
as
implementation that we used in Example 2. For the main NumPy and MatPlotLib
libraries, this is implemented as follows:
import
numpy
as
np
import
maplotlib.pyplot
as
plt
These statements import the entire library named in the
import
statement and associate
a prefix with the imported library:
np
and
plt
in the above examples. Functions from
within these libraries are then called by attaching the appropriate prefix with a period
before
the function name. Thus, the functions
sqrt
or
sin
from the NumPy library are
called using the syntax
np.sqrt
or
np.sin
; the functions
plot
or
xlabel
from the
maplotlib.pyplot
would be called using
plt.plot
or
plt.xlabel
.
Alternatively, the NumPy and MatPlotLib libraries can be called simply by writing
import
numpy
import
maplotlib.pyplot
When loaded this way, the
sqrt
function would be called as
numpy.sqrt
and the
plot
function would be called as
MatPlotLib.pyplot.plot
. The
import as
syntax allows you to define nicknames for
numpy
and
maplotlib.pyplot
. Nearly
any nickname can be chosen, but the Python community has settled on the nicknames
np
and
plt
for
numpy
and
maplotlib.pyplot
, so you are advised to stick with those.
Using the standard nicknames makes your code more readable.
You can also import a single functions or subset of functions from a module without
importing the entire module. For example, suppose you wanted to import just the natural
24
Chapter 2. Launching Python