Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Introduction to Python for Science 2013.pdf
Скачиваний:
60
Добавлен:
21.05.2015
Размер:
2.41 Mб
Скачать

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 MatPlotLib 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 order 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

Introduction to Python for Science, Release 0.9.23

log function log from NumPy. You could write

from numpy import log

To use the log function in a script, you would write

a = log(5)

which would assign the value 1.6094379124341003 to the variable a. If you wanted to import the three functions, log, sin, and cos, you would write

from numpy import log, sin, cos

and would similarly use them without an “np.” prefix. In general, we do not recommend using the the from module import ... way of importing functions. When reading code, t makes it harder to determine from which modules functions are imported, and can lead to clashes between similarly named functions from different modules. Nevertheless, you will see the form used in programs you encounter on the web and elsewhere so it is important to understand the syntax.

2.10 Getting help: documentation in IPython

Help is never far away when you are running the IPython shell. To obtain information on any valid Python or NumPy function, and many MatPlotLib functions, simply type help( function ), as illustrated here

In [1]: help(range)

range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.

Often, the information provided can be quite extensive and you might find it useful to clear the IPython window with the clear command so you can easily scroll back to find the beginning of the documentation. You may have also noticed that when you type the name of a function plus the opening parenthesis, IPython displays a window showing the first dozen lines or so of the documentation on that function.

2.10. Getting help: documentation in IPython

25

Introduction to Python for Science, Release 0.9.23

2.11 Programming is a detail-oriented activity

Now that you have a little experience with Python and computer programming, it’s time for an important reminder: Programming is a detail-oriented activity. To be good at computer programming, to avoid frustration when programming, you must pay attention to details. A misplaced or forgotten comma or colon can keep your code from working. Note that I did not say it can “keep your code from working well”; it can keep your code from working at all! Worse still, little errors can make your code give erroneous answers, where your code appears to work, but in fact does not! So pay attention to the details!

This raises a second point: sometimes your code will run but give the wrong answer because of a programming error or because of a more subtle error in your algorithm. For this reason, it is important to test your code to make sure it is behaving properly. Test it to make sure it gives the correct answers for cases where you already know the correct answer or where you have some independent means of checking it. Test it in limiting cases, that is, for cases that are at the extremes of the sets of parameters you will employ. Always test your code; this is a cardinal rule of programming.

26

Chapter 2. Launching Python

Introduction to Python for Science, Release 0.9.23

2.12 Exercises

1.A ball is thrown vertically up in the air from a height h0 above the ground at an initial velocity v0. Its subsequent height h and velocity v are given by the equations

h = h0 + v0t 12 gt2 v = v0 gt

where g = 9:8 is the acceleration due to gravity in m=s2. Write a script that finds the height h and velocity v at a time t after the ball is thrown. Start the script by setting h0 = 1:2 (meters) and v0 = 5:4 (m/s) and have your script print out the values of height and velocity (see Note about printing). Then use the script to find the height and velocity after 0.5 seconds. Then modify your script to find them after

2.0 seconds.

2.Write a script that defines the variables V0 = 10, a = 2:5, and z = 413 , and then evaluates the expression

V = V0 1

p

z

:

 

a2 + z2

Then find V for z = 823 and print it out (see Note about printing). Then find V for z = 13 by changing the value of z in your script.

3. Write a single Python script that calculates the following expressions:

(a)

 

2 + e2:8

 

 

p

 

 

 

 

 

 

 

 

13 2

 

 

 

 

 

(b)

 

1 (1 + ln 2) 3:5

 

 

 

 

 

 

 

 

 

1

+ p5

!

 

 

2

 

p

 

 

+ p2

(c)

sin

2

2

 

 

 

 

 

 

 

 

After running your script in the IPython shell, typing a, b, or c at the IPython prompt should yield the value of the expressions in (a), (b), or (c), respectively.

4. A quadratic equation with the general form

ax2 + bx + c = 0

has two solutions given by the quadratic formula p

x =

b b2 4ac

:

2a

 

 

2.12. Exercises

27

Introduction to Python for Science, Release 0.9.23

(a)Given a, b, and c as inputs, write a script that gives the numerical values of the two solutions. Write the constants a, b, and c as floats, and show that your script gives the correct solutions for a few test cases when the solutions are real numbers, that is, when the discriminant b2 4ac 0. Use the print function in your script, discussed at the end of Section 2.8.1 Scripting Example 1, to print out your two solutions.

(b)Written this way, however, your script gives an error message when the solutions are complex. For example, see what happens when a = 1, b = 2, and c = 3. You can fix this using statements in your script like a = a+0j after setting a to some float value. Thus, you can make the script work for any set of real inputs for a, b, and c. Again, use the print function to print out your two solutions.

28

Chapter 2. Launching Python

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]