没有合适的资源?快使用搜索试试~ 我知道了~
A Crash Course in Python for Scientists
需积分: 15 7 下载量 90 浏览量
2017-12-05
17:52:51
上传
评论
收藏 2.08MB PDF 举报
温馨提示
试读
55页
A Crash Course in Python for Scientists;A Crash Course in Python for Scientists
资源推荐
资源详情
资源评论
A Crash Course in Python for Scientists
Rick Muller (http://www.cs.sandia.gov/~rmuller/), Sandia National Laboratories
version 0.6
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License
(http://creativecommons.org/licenses/by-sa/3.0/deed.en_US).
Why Python?
Python is the programming language of choice for many scientists to a large degree because it offers a great deal of power
to analyze and model scientific data with relatively little overhead in terms of learning, installation or development time. It is
a language you can pick up in a weekend, and use for the rest of one's life.
The Python Tutorial (http://docs.python.org/2/tutorial/) is a great place to start getting a feel for the language. To
complement this material, I taught a Python Short Course (http://www.wag.caltech.edu/home/rpm/python_course/) years
ago to a group of computational chemists during a time that I was worried the field was moving too much in the direction of
using canned software rather than developing one's own methods. I wanted to focus on what working scientists needed to
be more productive: parsing output of other programs, building simple models, experimenting with object oriented
programming, extending the language with C, and simple GUIs.
I'm trying to do something very similar here, to cut to the chase and focus on what scientists need. In the last year or so, the
IPython Project (http://ipython.org) has put together a notebook interface that I have found incredibly valuable. A large
number of people have released very good IPython Notebooks that I have taken a huge amount of pleasure reading
through. Some ones that I particularly like include:
Rob Johansson's excellent notebooks (http://jrjohansson.github.io/), including Scientific Computing with Python
(https://github.com/jrjohansson/scientific-python-lectures) and Computational Quantum Physics with QuTiP
(https://github.com/jrjohansson/qutip-lectures) lectures;
XKCD style graphs in matplotlib
(http://nbviewer.ipython.org/url/jakevdp.github.com/downloads/notebooks/XKCD_plots.ipynb);
A collection of Notebooks for using IPython effectively
(https://github.com/ipython/ipython/tree/master/examples/notebooks#a-collection-of-notebooks-for-using-
ipython-effectively)
A gallery of interesting IPython Notebooks (https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-
IPython-Notebooks)
I find IPython notebooks an easy way both to get important work done in my everyday job, as well as to communicate what
I've done, how I've done it, and why it matters to my coworkers. I find myself endlessly sweeping the IPython subreddit
(http://ipython.reddit.com) hoping someone will post a new notebook. In the interest of putting more notebooks out into the
wild for other people to use and enjoy, I thought I would try to recreate some of what I was trying to get across in the
original Python Short Course, updated by 15 years of Python, Numpy, Scipy, Matplotlib, and IPython development, as well
as my own experience in using Python almost every day of this time.
What You Need to Install
There are two branches of current releases in Python: the older-syntax Python 2, and the newer-syntax Python 3. This
schizophrenia is largely intentional: when it became clear that some non-backwards-compatible changes to the language
were necessary, the Python dev-team decided to go through a five-year (or so) transition, during which the new language
features would be introduced and the old language was still actively maintained, to make such a transition as easy as
possible. We're now (2013) past the halfway point, and, IMHO, at the first time when I'm considering making the change to
Python 3.
Nonetheless, I'm going to write these notes with Python 2 in mind, since this is the version of the language that I use in my
day-to-day job, and am most comfortable with. If these notes are important and are valuable to people, I'll be happy to
rewrite the notes using Python 3.
With this in mind, these notes assume you have a Python distribution that includes:
Python (http://www.python.org) version 2.7;
Numpy (http://www.numpy.org), the core numerical extensions for linear algebra and multidimensional arrays;
Scipy (http://www.scipy.org), additional libraries for scientific programming;
Matplotlib (http://matplotlib.sf.net), excellent plotting and graphing libraries;
IPython (http://ipython.org), with the additional libraries required for the notebook interface.
A good, easy to install option that supports Mac, Windows, and Linux, and that has all of these packages (and much more)
is the Entought Python Distribution (https://www.enthought.com/products/epd), also known as EPD, which appears to be
changing its name to Enthought Canopy. Enthought is a commercial company that supports a lot of very good work in
scientific Python development and application. You can either purchase a license to use EPD, or there is also a free version
(https://www.enthought.com/products/epd/free/) that you can download and install.
Here are some other alternatives, should you not want to use EPD:
Linux Most distributions have an installation manager. Redhat has yum, Ubuntu has apt-get. To my knowledge, all of these
packages should be available through those installers.
Mac I use Macports (http://www.macports.org/), which has up-to-date versions of all of these packages.
Windows The PythonXY (https://code.google.com/p/pythonxy/) package has everything you need: install the package, then
go to Start > PythonXY > Command Prompts > IPython notebook server.
Cloud This notebook is currently not running on the IPython notebook viewer (http://nbviewer.ipython.org/), but will be
shortly, which will allow the notebook to be viewed but not interactively. I'm keeping an eye on Wakari
(http://www.wakari.io), from Continuum Analytics (http://continuum.io/), which is a cloud-based IPython notebook. Wakari
appears to support free accounts as well. Continuum is a company started by some of the core Enthought Numpy/Scipy
people focusing on big data.
Continuum also supports a bundled, multiplatform Python package called Anaconda (https://store.continuum.io/) that I'll
also keep an eye on.
I. Python Overview
This is a quick introduction to Python. There are lots of other places to learn the language more thoroughly. I have collected
a list of useful links, including ones to other learning resources, at the end of this notebook. If you want a little more depth,
Python Tutorial (http://docs.python.org/2/tutorial/) is a great place to start, as is Zed Shaw's Learn Python the Hard Way
(http://learnpythonthehardway.org/book/).
The lessons that follow make use of the IPython notebooks. There's a good introduction to notebooks in the IPython
notebook documentation (http://ipython.org/notebook.html) that even has a nice video (http://www.youtube.com/watch?
v=H6dLGQw9yFQ#!) on how to use the notebooks. You should probably also flip through the IPython tutorial
(http://ipython.org/ipython-doc/dev/interactive/tutorial.html) in your copious free time.
Briefly, notebooks have code cells (that are generally followed by result cells) and text cells. The text cells are the stuff that
you're reading now. The code cells start with "In []:" with some number generally in the brackets. If you put your cursor in
the code cell and hit Shift-Enter, the code will run in the Python interpreter and the result will print out in the output cell. You
can then change things around and see whether you understand what's going on. If you need to know more, see the
IPython notebook documentation (http://ipython.org/notebook.html) or the IPython tutorial (http://ipython.org/ipython-
doc/dev/interactive/tutorial.html).
Using Python as a Calculator
Many of the things I used to use a calculator for, I now use Python for:
In[1]:
2+2
In[2]:
(50-5*6)/4
(If you're typing this into an IPython notebook, or otherwise using notebook file, you hit shift-Enter to evaluate a cell.)
There are some gotchas compared to using a normal calculator.
In[3]:
7/3
Python integer division, like C or Fortran integer division, truncates the remainder and returns an integer. At least it does in
version 2. In version 3, Python returns a floating point number. You can get a sneak preview of this feature in Python 2 by
importing the module from the future features:
from __future__ import division
Alternatively, you can convert one of the integers to a floating point number, in which case the division function returns
another floating point number.
Out[1]: 4
Out[2]:
5
Out[3]: 2
In[4]:
7/3.
In[5]:
7/float(3)
In the last few lines, we have sped by a lot of things that we should stop for a moment and explore a little more fully. We've
seen, however briefly, two different data types: integers, also known as whole numbers to the non-programming world, and
floating point numbers, also known (incorrectly) as decimal numbers to the rest of the world.
We've also seen the first instance of an import statement. Python has a huge number of libraries included with the
distribution. To keep things simple, most of these variables and functions are not accessible from a normal Python
interactive session. Instead, you have to import the name. For example, there is a math module containing many useful
functions. To access, say, the square root function, you can either first
from math import sqrt
and then
In[6]:
sqrt(81)
or you can simply import the math library itself
In[7]:
import math
math.sqrt(81)
You can define variables using the equals (=) sign:
In[8]:
width = 20
length = 30
area = length*width
area
If you try to access a variable that you haven't yet defined, you get an error:
In[9]:
volume
and you need to define it:
In[]:
depth = 10
volume = area*depth
volume
You can name a variable almost anything you want. It needs to start with an alphabetical character or "_", can contain
alphanumeric charcters plus underscores ("_"). Certain words, however, are reserved for the language:
and, as, assert, break, class, continue, def, del, elif, else, except,
exec, finally, for, from, global, if, import, in, is, lambda, not, or,
pass, print, raise, return, try, while, with, yield
Trying to define a variable using one of these will result in a syntax error:
Out[4]: 2.3333333333333335
Out[5]:
2.3333333333333335
Out[6]: 9.0
Out[7]: 9.0
Out[8]:
600
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-0c7fc58f9268> in <module>()
----> 1 volume
NameError: name 'volume' is not defined
In[10]:
return = 0
The Python Tutorial (http://docs.python.org/2/tutorial/introduction.html#using-python-as-a-calculator) has more on using
Python as an interactive shell. The IPython tutorial (http://ipython.org/ipython-doc/dev/interactive/tutorial.html) makes a nice
complement to this, since IPython has a much more sophisticated iteractive shell.
Strings
Strings are lists of printable characters, and can be defined using either single quotes
In[11]:
'Hello, World!'
or double quotes
In[12]:
"Hello, World!"
But not both at the same time, unless you want one of the symbols to be part of the string.
In[13]:
"He's a Rebel"
In[14]:
'She asked, "How are you today?"'
Just like the other two data objects we're familiar with (ints and floats), you can assign a string to a variable
In[15]:
greeting = "Hello, World!"
The print statement is often used for printing character strings:
In[16]:
print greeting
But it can also print data types other than strings:
In[17]:
print "The area is ",area
In the above snipped, the number 600 (stored in the variable "area") is converted into a string before being printed out.
You can use the + operator to concatenate strings together:
In[18]:
statement = "Hello," + "World!"
print statement
Don't forget the space between the strings, if you want one there.
In[19]:
statement = "Hello, " + "World!"
print statement
You can use + to concatenate multiple strings in a single statement:
File "<ipython-input-10-2b99136d4ec6>", line 1
return = 0
^
SyntaxError: invalid syntax
Out[11]:
'Hello, World!'
Out[12]: 'Hello, World!'
Out[13]: "He's a Rebel"
Out[14]:
'She asked, "How are you today?"'
Hello, World!
The area is 600
Hello,World!
Hello, World!
In[20]:
print "This " + "is " + "a " + "longer " + "statement."
If you have a lot of words to concatenate together, there are other, more efficient ways to do this. But this is fine for linking a
few strings together.
Lists
Very often in a programming language, one wants to keep a group of similar items together. Python does this using a data
type called lists.
In[21]:
days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
You can access members of the list using the index of that item:
In[22]:
days_of_the_week[2]
Python lists, like C, but unlike Fortran, use 0 as the index of the first element of a list. Thus, in this example, the 0 element is
"Sunday", 1 is "Monday", and so on. If you need to access the nth element from the end of the list, you can use a negative
index. For example, the -1 element of a list is the last element:
In[23]:
days_of_the_week[-1]
You can add additional items to the list using the .append() command:
In[24]:
languages = ["Fortran","C","C++"]
languages.append("Python")
print languages
The range() command is a convenient way to make sequential lists of numbers:
In[25]:
range(10)
Note that range(n) starts at 0 and gives the sequential list of integers less than n. If you want to start at a different number,
use range(start,stop)
In[26]:
range(2,8)
The lists created above with range have a step of 1 between elements. You can also give a fixed step size via a third
command:
In[27]:
evens = range(0,20,2)
evens
In[28]:
evens[3]
Lists do not have to hold the same data type. For example,
In[29]:
["Today",7,99.3,""]
However, it's good (but not essential) to use lists for similar objects that are somehow logically connected. If you want to
group different data types together into a composite data object, it's best to use tuples, which we will learn about below.
This is a longer statement.
Out[22]: 'Tuesday'
Out[23]:
'Saturday'
['Fortran', 'C', 'C++', 'Python']
Out[25]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Out[26]:
[2, 3, 4, 5, 6, 7]
Out[27]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Out[28]:
6
Out[29]: ['Today', 7, 99.3, '']
剩余54页未读,继续阅读
资源评论
eeabcde
- 粉丝: 0
- 资源: 15
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功