Introduction to Python


Christof Angermueller

@cangermueller

http://cangermueller.com

http://goo.gl/cAU9Tq

About me

Studies 2008-2013

PhD 2014-

Why Python?

Increasing popularity

Good trade-off performance vs. productivity

Many packages

Fundamental types

In [2]:
a = 10
a
Out[2]:
10
In [3]:
type(a)
Out[3]:
int
In [5]:
a = 1.0
a
Out[5]:
1.0
In [6]:
type(a)
Out[6]:
float
In [7]:
a = 1 / 2
a
Out[7]:
0.5
In [8]:
type(a)
Out[8]:
float
In [9]:
s = 'Hello world!'
s
Out[9]:
'Hello world!'
In [10]:
len(s)
Out[10]:
12
In [13]:
s[1]
Out[13]:
'e'
In [14]:
'Foo' + 'Bar'
Out[14]:
'FooBar'

list

In [15]:
l = [1, 2, 3]
l
Out[15]:
[1, 2, 3]
In [16]:
type(l)
Out[16]:
list
In [18]:
l = list(range(1, 10))
l
Out[18]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [19]:
len(l)
Out[19]:
9
In [20]:
l[-1]
Out[20]:
9
In [21]:
l[:5]
Out[21]:
[1, 2, 3, 4, 5]
In [22]:
l[5:]
Out[22]:
[6, 7, 8, 9]
In [24]:
l[::2]
Out[24]:
[1, 3, 5, 7, 9]
In [25]:
l[::-1]
Out[25]:
[9, 8, 7, 6, 5, 4, 3, 2, 1]
In [26]:
l.append([10, 11, 12])
l
Out[26]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 12]]
In [27]:
l[-1]
Out[27]:
[10, 11, 12]
In [29]:
l.extend([13, 14, 15])
l
Out[29]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 12], 13, 14, 15, 13, 14, 15]
In [22]:
l = range(100000)

dict

In [30]:
d = {'a': 1, 'b':2, 'c': 3}
d
Out[30]:
{'c': 3, 'a': 1, 'b': 2}
In [31]:
type(d)
Out[31]:
dict
In [32]:
d['a']
Out[32]:
1
In [33]:
d.keys()
Out[33]:
dict_keys(['c', 'a', 'b'])
In [34]:
d.values()
Out[34]:
dict_values([3, 1, 2])
In [36]:
for k, v in d.items():
    print(k, v)
c 3
a 1
b 2

set

In [37]:
s = {'a', 'b', 'c', 'c'}
s
Out[37]:
{'a', 'b', 'c'}
In [39]:
type(s)
Out[39]:
set
In [40]:
's' in s
Out[40]:
False
In [41]:
s.union({'a', 'b', 'f'})
Out[41]:
{'a', 'b', 'c', 'f'}

Loops and comprehensions

In [42]:
def square_loop(l):
    rv = []
    for v in l:
        rv.append(v**2)
    return rv
In [44]:
square_loop(range(5))
Out[44]:
[0, 1, 4, 9, 16]
In [45]:
def square_comprehension(l):
    return [v**2 for v in l]
In [46]:
square_comprehension(range(5))
Out[46]:
[0, 1, 4, 9, 16]
In [50]:
l = range(100000)
In [51]:
%timeit square_loop(l)
10 loops, best of 3: 46.3 ms per loop
In [52]:
%timeit square_comprehension(l)
10 loops, best of 3: 41.3 ms per loop

Importing packages

In [53]:
import math
In [54]:
math.pi
Out[54]:
3.141592653589793
In [55]:
math.sqrt(2)
Out[55]:
1.4142135623730951
In [56]:
math.exp(1)
Out[56]:
2.718281828459045
In [57]:
math.log(math.e)
Out[57]:
1.0

Further readings