Python basics

Nikolay Koldunov

koldunovn@gmail.com

This is part of Python for Geosciences notes.

================

Variables

Python uses duck typing

Int


In [1]:
a = 10

In [2]:
a


Out[2]:
10

In [3]:
type(a)


Out[3]:
int

Float


In [4]:
z = 10.
z


Out[4]:
10.0

In [5]:
type(z)


Out[5]:
float

String


In [6]:
b = '2'
b


Out[6]:
'2'

Some operations are not allowed on different types:


In [7]:
a+b


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-f1d53b280433> in <module>()
----> 1 a+b

TypeError: unsupported operand type(s) for +: 'int' and 'str'

But some of them are allowed:


In [8]:
a*b


Out[8]:
'2222222222'

Might be a source of confusion :)

String variables can be combined:


In [9]:
c = ' guys walk into a bar'
c


Out[9]:
' guys walk into a bar'

In [10]:
b+c


Out[10]:
'2 guys walk into a bar'

In order to include variable of another type in to string you have to convert it:


In [11]:
str(a)+c


Out[11]:
'10 guys walk into a bar'

Everything is an object

In IPython you can get the list of object's methods and attributes by typing dot and pressing TAB:


In [ ]:
c.

Methods are basically default functions that can be applied to our variable:


In [13]:
c.upper()


Out[13]:
' GUYS WALK INTO A BAR'

In [14]:
c.title()


Out[14]:
' Guys Walk Into A Bar'

In [15]:
c.count('a')


Out[15]:
3

In [16]:
c.find('into')


Out[16]:
11

If you need help on method in IPython type something like:


In [17]:
c.find?

Or open bracket and press TAB:


In [ ]:
c.find(

Int variable is also an object:


In [18]:
a.bit_length()


Out[18]:
4

Methods can be combined (kind of a pipeline)


In [19]:
c.title().count('a').bit_length()


Out[19]:
2

Lists

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:


In [20]:
l = [1,2,3,4,5]
l


Out[20]:
[1, 2, 3, 4, 5]

Sort of similar to Matlab variables, but not exactly.

Values in list can be any type:


In [21]:
l = ['one', 'two', 'three', 'four', 'five']
l


Out[21]:
['one', 'two', 'three', 'four', 'five']

Combined


In [22]:
l = ['one', 2, 'three', 4.0, 3+2]
l


Out[22]:
['one', 2, 'three', 4.0, 5]

Any type means ANY type:


In [23]:
l = ['one', 2, 'three', [1,2,3,4,5], 3+2]
l


Out[23]:
['one', 2, 'three', [1, 2, 3, 4, 5], 5]

You can access list values by index:


In [24]:
l[0]


Out[24]:
'one'

Oh, yes, indexing starts with zero, so for Matlab users the zero is the new one :) See discussion on the matter here.


In [25]:
l[1]


Out[25]:
2

Let's have a look at the 4th element of our list:


In [26]:
l[3]


Out[26]:
[1, 2, 3, 4, 5]

It's also a list, and its values can be accessed by indexes as well:


In [27]:
l[3][4]


Out[27]:
5

You also can acces multiple elements of the list using slices:


In [28]:
l[1:3]


Out[28]:
[2, 'three']

Slice will start with the first slice index and go up to but not including the second slice index.


In [29]:
l[3]


Out[29]:
[1, 2, 3, 4, 5]

Control Structures

For loop:

This loop will print all elements from the list l


In [30]:
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:


In [31]:
for element in l:
print element


  File "<ipython-input-31-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:


In [32]:
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:


In [33]:
range(5)


Out[33]:
[0, 1, 2, 3, 4]

Branches

We are not going to use branches in this notes, but this is how they look like just as another example of indentation use:


In [34]:
x = -1
if x > 0:
   print "Melting"
elif x == 0:
   print "Zero"
else:
   print "Freezing"


Freezing

Modules

Pure python does not do much. 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.


In [35]:
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:


In [36]:
response = urllib2.urlopen('ftp://ftp.zmaw.de/')
html = response.read()
html.splitlines()


Out[36]:
['dr-xr-x---  11 ftp      ftp          4096 Jun 14 03:15 incoming',
 'dr-xr-x---  39 ftp      ftp          4096 Jun 16 15:02 outgoing']

Another option is to import it like this:


In [37]:
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:


In [38]:
response = urlopen('ftp://ftp.zmaw.de/')
html = response.read()
html.splitlines()


Out[38]:
['dr-xr-x---  11 ftp      ftp          4096 Jun 14 03:15 incoming',
 'dr-xr-x---  39 ftp      ftp          4096 Jun 16 15:02 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.


In [ ]:
whos

You can import only function that you need:


In [40]:
from urllib2 import urlopen

In [41]:
response = urlopen('ftp://ftp.zmaw.de/')
html = response.read()
html.splitlines()


Out[41]:
['dr-xr-x---  11 ftp      ftp          4096 Jun 14 03:15 incoming',
 'dr-xr-x---  39 ftp      ftp          4096 Jun 16 15:02 outgoing']

Or import library as alias in order to avoid extensive typing:


In [42]:
import urllib2 as ul

In [43]:
response = ul.urlopen('ftp://ftp.zmaw.de/')
html = response.read()
html.splitlines()


Out[43]:
['dr-xr-x---  11 ftp      ftp          4096 Jun 14 03:15 incoming',
 'dr-xr-x---  39 ftp      ftp          4096 Jun 16 15:02 outgoing']

Links: