This is part of Python for Geosciences notes.
================
Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C. The language provides constructs intended to enable clear programs on both a small and large scale.
-- From Wikipedia, the free encyclopedia
Python uses duck typing
a = 10
a
10
type(a)
int
z = 10.
z
10.0
type(z)
float
b = '2'
b
'2'
Some operations are not allowed on different types:
a+b
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-f1d53b280433> in <module>() ----> 1 a+b TypeError: unsupported operand type(s) for +: 'int' and 'str'
But some of them are allowed:
a*b
'2222222222'
Might be a source of confusion :)
String variables can be combined:
c = ' guys walk into a bar'
c
' guys walk into a bar'
b+c
'2 guys walk into a bar'
In order to include variable of another type in to string you have to convert it:
str(a)+c
'10 guys walk into a bar'
In IPython you can get the list of object's methods and attributes by typing dot and pressing TAB:
c.
' guys walk into a bar'
Methods are basically default functions that can be applied to our variable:
c.upper()
' GUYS WALK INTO A BAR'
c.title()
' Guys Walk Into A Bar'
c.count('a')
3
c.find('into')
11
If you need help on method in IPython type something like:
c.find?
Or open bracket and press TAB:
c.find(
Int variable is also an object:
a.bit_length()
4
Methods can be combined (kind of a pipeline)
c.title().count('a').bit_length()
2
There are several other interesting variable types in Python, but the one we would need the most is the list.
In order to create list put coma separated values in square brackets:
l = [1,2,3,4,5]
l
[1, 2, 3, 4, 5]
Sort of similar to Matlab variables, but not exactly.
Values in list can be any type:
l = ['one', 'two', 'three', 'four', 'five']
l
['one', 'two', 'three', 'four', 'five']
Combined
l = ['one', 2, 'three', 4.0, 3+2]
l
['one', 2, 'three', 4.0, 5]
Any type means ANY type:
l = ['one', 2, 'three', [1,2,3,4,5], 3+2]
l
['one', 2, 'three', [1, 2, 3, 4, 5], 5]
You can access list values by index:
l[0]
'one'
Oh, yes, indexing starts with zero, so for Matlab users the zero is the new one :) See discussion on the matter here.
l[1]
2
Let's have a look at the 4th element of our list:
l[3]
[1, 2, 3, 4, 5]
It's also a list, and its values can be accessed by indexes as well:
l[3][4]
5
You also can acces multiple elements of the list using slices:
l[1:3]
[2, 'three']
Slice will start with the first slice index and go up to but not including the second slice index.
l[3]
[1, 2, 3, 4, 5]
This loop will print all elements from the list l
l = ['one', 2, 'three', [1,2,3,4,5], 3+2]
for element in l:
print element
one 2 three [1, 2, 3, 4, 5] 5
Two interesting thins here. First: indentation, it's in the code, you must use it, otherwise code will not work:
for element in l:
print element
File "<ipython-input-34-7d2140ae42dc>", line 2 print element ^ IndentationError: expected an indented block
Second - you can iterate through the elements of the list. There is an option to iterate through a bunch of numbers as we used to in Matlab:
for index in range(5):
print(l[index])
one 2 three [1, 2, 3, 4, 5] 5
where range is just generating a list with sequence of numbers:
range(5)
[0, 1, 2, 3, 4]
We are not going to use branches in this notes, but this is how they look like just as another example of indentation use:
x = -1
if x > 0:
print "Melting"
elif x == 0:
print "Zero"
else:
print "Freezing"
Freezing
Pure python does not do much. Even IPython with pylab enabled can do only limited number of things. To do some specific tasks you need to import modules. Here I am going to demonstrate several ways to do so.
The most common one is to import complete library. In this example we import urllib2 - a library for opening URLs using a variety of protocols.
import urllib2
Here we get information from some ftp site. Note how function urlopen is called. We have to use name of the library, then dot, then name of the function from the library:
response = urllib2.urlopen('ftp://ftp.zmaw.de/')
html = response.read()
html.splitlines()
['dr-xr-x--- 17 ftp ftp 20480 Oct 26 03:15 incoming', 'dr-xr-x--- 51 ftp ftp 12288 Oct 26 03:30 outgoing']
Another option is to import it like this:
from urllib2 import *
In this case all functions will be imported in to the name-space and you can use urlopen directly, without typing the name of the library first:
response = urlopen('ftp://ftp.zmaw.de/')
html = response.read()
html.splitlines()
['dr-xr-x--- 17 ftp ftp 20480 Oct 26 03:15 incoming', 'dr-xr-x--- 51 ftp ftp 12288 Oct 26 03:30 outgoing']
But generally I think it's a bad idea, because your name-space is populated by things that you don't really need and it's hard to tell where the function comes from.
whos
Variable Type Data/Info ------------------------------------------------------------------------- AbstractBasicAuthHandler classobj urllib2.AbstractBasicAuthHandler AbstractDigestAuthHandler classobj urllib2.AbstractDigestAuthHandler AbstractHTTPHandler classobj urllib2.AbstractHTTPHandler BaseHandler classobj urllib2.BaseHandler CacheFTPHandler classobj urllib2.CacheFTPHandler FTPHandler classobj urllib2.FTPHandler FileHandler classobj urllib2.FileHandler HTTPBasicAuthHandler classobj urllib2.HTTPBasicAuthHandler HTTPCookieProcessor classobj urllib2.HTTPCookieProcessor HTTPDefaultErrorHandler classobj urllib2.HTTPDefaultErrorHandler HTTPDigestAuthHandler classobj urllib2.HTTPDigestAuthHandler HTTPError type <class 'urllib2.HTTPError'> HTTPErrorProcessor classobj urllib2.HTTPErrorProcessor HTTPHandler classobj urllib2.HTTPHandler HTTPPasswordMgr classobj urllib2.HTTPPasswordMgr HTTPPasswordMgrWithDefaultRealm classobj urllib2.HTTPPasswordMgrWithDefaultRealm HTTPRedirectHandler classobj urllib2.HTTPRedirectHandler HTTPSHandler classobj urllib2.HTTPSHandler OpenerDirector classobj urllib2.OpenerDirector ProxyBasicAuthHandler classobj urllib2.ProxyBasicAuthHandler ProxyDigestAuthHandler classobj urllib2.ProxyDigestAuthHandler ProxyHandler classobj urllib2.ProxyHandler Request classobj urllib2.Request StringIO builtin_function_or_method <built-in function StringIO> URLError type <class 'urllib2.URLError'> UnknownHandler classobj urllib2.UnknownHandler a int 10 addinfourl classobj urllib.addinfourl b str 2 base64 module <module 'base64' from '/u<...>ib/python2.7/base64.pyc'> bisect module <module 'bisect' from '/u<...>ib/python2.7/bisect.pyc'> build_opener function <function build_opener at 0x323b578> c str guys walk into a bar element int 5 ftpwrapper classobj urllib.ftpwrapper getproxies function <function getproxies_environment at 0x1ef1050> hashlib module <module 'hashlib' from '/<...>b/python2.7/hashlib.pyc'> \n httplib module <module 'httplib' from '/<...>b/python2.7/httplib.pyc'> index int 4 install_opener function <function install_opener at 0x323b230> l list n=5 localhost function <function localhost at 0x1eb1e60> mimetools module <module 'mimetools' from <...>python2.7/mimetools.pyc'> os module <module 'os' from '/usr/lib/python2.7/os.pyc'> parse_http_list function <function parse_http_list at 0x323e7d0> parse_keqv_list function <function parse_keqv_list at 0x323cd70> posixpath module <module 'posixpath' from <...>python2.7/posixpath.pyc'> proxy_bypass function <function proxy_bypass_environment at 0x1ef10c8> quote function <function quote at 0x1ee5e60> randombytes function <function randombytes at 0x323c668> re module <module 're' from '/usr/lib/python2.7/re.pyc'> request_host function <function request_host at 0x323b2a8> response urllib.addinfourl <addinfourl at 54345600 w<...>ct object at 0x33af350>>> socket module <module 'socket' from '/u<...>ib/python2.7/socket.pyc'> splitattr function <function splitattr at 0x1ee5c80> splithost function <function splithost at 0x1ee5938> splitpasswd function <function splitpasswd at 0x1ee5a28> splitport function <function splitport at 0x1ee5aa0> splittag function <function splittag at 0x1ee5c08> splittype function <function splittype at 0x1ee58c0> splituser function <function splituser at 0x1ee59b0> splitvalue function <function splitvalue at 0x1ee5cf8> time module <module 'time' (built-in)> unquote function <function unquote at 0x1ee5d70> url2pathname function <function url2pathname at 0x1eb1938> urllib2 module <module 'urllib2' from '/<...>b/python2.7/urllib2.pyc'> urlopen function <function urlopen at 0x3238b90> urlparse module <module 'urlparse' from '<...>/python2.7/urlparse.pyc'> x int -1 z float 10.0
You can import only function that you need:
from urllib2 import urlopen
response = urlopen('ftp://ftp.zmaw.de/')
html = response.read()
html.splitlines()
['dr-xr-x--- 16 ftp ftp 20480 Oct 23 15:51 incoming', 'dr-xr-x--- 49 ftp ftp 12288 Oct 23 03:30 outgoing']
Or import library as alias in order to avoid extensive typing:
import urllib2 as ul
response = ul.urlopen('ftp://ftp.zmaw.de/')
html = response.read()
html.splitlines()
['dr-xr-x--- 17 ftp ftp 20480 Oct 26 03:15 incoming', 'dr-xr-x--- 51 ftp ftp 12288 Oct 26 03:30 outgoing']