Introduction to Python

Resources

Python for Science

More extensive set of notes focusing on scientific computation with Python - probably more useful as a reference. Overlpas with our first few lectures.

Coding Challenges

If you learn best by solving puzzles

Overview

In [1]:
# packages, modules, imports, namespaces
import numpy as np
from scipy.misc import factorial

# function definition with default arguments
def poisson_pmf(k, mu=1):
    """Poisson PMF for value k with rate mu."""
    return mu**k*np.exp(-mu)/factorial(k)
In [2]:
# Jupyter notebook "magic" function
# Sets up "inline" plotting
%matplotlib inline

# Importing the searborn plotting library and setting defaults
import warnings

with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    import seaborn as sns
    sns.set_context("notebook", font_scale=1.5)

# Variable assignment
n = np.arange(10) # [0, 1, 2, ..., 0]

# Note that poisson_pmf is vectorized
sns.barplot(n, poisson_pmf(n, 2))

# pass is a do-nothing statement -
# Used here to suppresss printing of return value for sns.barplot()
pass
/Users/cliburn/anaconda/envs/py35/lib/python3.5/site-packages/matplotlib/__init__.py:892: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
_images/01_Introduction_To_Python_4_1.png

Types

In [3]:
# Boolean

True, False
Out[3]:
(True, False)
In [4]:
# Integer
0, 1, 23, int(3.8)
Out[4]:
(0, 1, 23, 3)
In [5]:
# Float
1.2, 3.14, float(2)
Out[5]:
(1.2, 3.14, 2.0)
In [6]:
# Complex
1 + 2j, complex(23)
Out[6]:
((1+2j), (23+0j))
In [7]:
# String
('abc', "abc",
"""abc
def
ghi""",
r'\t')
Out[7]:
('abc', 'abc', 'abc\ndef\nghi', '\\t')
In [8]:
# None
None
In [9]:
type(3)
Out[9]:
int
In [10]:
type(poisson_pmf)
Out[10]:
function

Operators

In [11]:
2 * 3
Out[11]:
6
In [12]:
2 ** 3
Out[12]:
8
In [13]:
7 /3
Out[13]:
2.3333333333333335
In [14]:
7 // 3
Out[14]:
2
In [15]:
2 < 3
Out[15]:
True
In [16]:
7 % 3
Out[16]:
1
In [17]:
1 == 1
Out[17]:
True
In [18]:
1 != 2
Out[18]:
True
In [19]:
a = [1,2,3]
b = a
c = [1,2,3]
In [20]:
b == a
Out[20]:
True
In [21]:
b is a
Out[21]:
True
In [22]:
c == a
Out[22]:
True
In [23]:
c is a
Out[23]:
False
In [24]:
np.array([1,2,3]) @ np.array([1,2,3])
Out[24]:
14
In [25]:
True or False, True | False
Out[25]:
(True, True)
In [26]:
True and False, False & True
Out[26]:
(False, False)
In [27]:
2 << 4
Out[27]:
32
In [28]:
fruits = ['apple', 'banana', 'cherry', 'durian', 'eggplant', 'fig']
'durian' in fruits
Out[28]:
True

The operator module

Provides versions of operators as functions useful for the functional programming style.

In [29]:
import operator as op

op.mul(3, 4)
Out[29]:
12
In [30]:
from functools import reduce

reduce(op.mul, [2,3,4,5], 1)
Out[30]:
120

Names, assignment and identity

In [31]:
# Create some object (the list [1,2,3]) on the RHS and assign it to the name on the LHS
In [32]:
a = [1,2,3]
In [33]:
a
Out[33]:
[1, 2, 3]
In [34]:
# Find the identity (address in memory in CPython) of the object named a
In [35]:
id(a)
Out[35]:
4522333704
In [36]:
# Give the object named as a another name b
In [37]:
b = a
In [38]:
b
Out[38]:
[1, 2, 3]
In [39]:
# b is just another name for the object also named a
# So the identity is the same
id(b)
Out[39]:
4522333704
In [40]:
# Create a new object (the list [1,23]) and give it a name c
In [41]:
c = [1,2,3]
In [42]:
c
Out[42]:
[1, 2, 3]
In [43]:
# The object named c has a different identity from the object with names a, b
id(c)
Out[43]:
4561360264
In [44]:
a
Out[44]:
[1, 2, 3]
In [45]:
b[0] = 99
In [46]:
a
Out[46]:
[99, 2, 3]
In [47]:
c
Out[47]:
[1, 2, 3]

Augmented assignment

In [48]:
x = 1
In [49]:
x += 2
x
Out[49]:
3
In [50]:
x **= 3
x
Out[50]:
27

Collections

Tuples

In [51]:
course = ('STA-663', 2016, 'Spring', 50)
In [52]:
course[0]
Out[52]:
'STA-663'
In [53]:
course[1]
Out[53]:
2016
In [54]:
course[-1]
Out[54]:
50

Tuple unpacking

In [55]:
name, year, semester, size = course
In [56]:
semester
Out[56]:
'Spring'
In [57]:
name, *when, size = course
In [58]:
name
Out[58]:
'STA-663'
In [59]:
size
Out[59]:
50
In [60]:
when
Out[60]:
[2016, 'Spring']

Named tuples

In [61]:
import collections
In [62]:
course = collections.namedtuple('course', ['name', 'year','semester', 'size'])
In [63]:
sta_663 = course(name = 'STA-663', year=2016, size=50, semester='Spring')
In [64]:
sta_663
Out[64]:
course(name='STA-663', year=2016, semester='Spring', size=50)
In [65]:
name, *when, size = sta_663
In [66]:
when
Out[66]:
[2016, 'Spring']
In [67]:
sta_663[-1]
Out[67]:
50
In [68]:
sta_663.size
Out[68]:
50

Lists

In [69]:
x = [1,2,3,4,5]
In [70]:
x[1:4]
Out[70]:
[2, 3, 4]
In [71]:
x[-1] = 10
x
Out[71]:
[1, 2, 3, 4, 10]
In [72]:
x[::2]
Out[72]:
[1, 3, 10]
In [73]:
x[::-1]
Out[73]:
[10, 4, 3, 2, 1]
In [74]:
x + x
Out[74]:
[1, 2, 3, 4, 10, 1, 2, 3, 4, 10]
In [75]:
x * 3
Out[75]:
[1, 2, 3, 4, 10, 1, 2, 3, 4, 10, 1, 2, 3, 4, 10]
In [76]:
x.append(20)
x
Out[76]:
[1, 2, 3, 4, 10, 20]
In [77]:
x.extend([3,4,5])
x
Out[77]:
[1, 2, 3, 4, 10, 20, 3, 4, 5]
In [78]:
x.index(10)
Out[78]:
4
In [79]:
x.count(3)
Out[79]:
2

Sets

In [80]:
s = {1,1,2,3,4}
s
Out[80]:
{1, 2, 3, 4}
In [81]:
s.add(2)
s
Out[81]:
{1, 2, 3, 4}
In [82]:
s.add(5)
s
Out[82]:
{1, 2, 3, 4, 5}

Set operations and equivalent methods

In [83]:
s & {5,6,7}, s.intersection({5,6,7})
Out[83]:
({5}, {5})
In [84]:
s | {5,6,7}, s.union({5,6,7})
Out[84]:
({1, 2, 3, 4, 5, 6, 7}, {1, 2, 3, 4, 5, 6, 7})
In [85]:
s - {5,6,7}, s.difference({5,6,7})
Out[85]:
({1, 2, 3, 4}, {1, 2, 3, 4})
In [86]:
s ^ {5,6,7}, s.symmetric_difference({5,6,7})
Out[86]:
({1, 2, 3, 4, 6, 7}, {1, 2, 3, 4, 6, 7})

Dictionary

In [87]:
d = {'a': 1, 'b':2, 'c':3}
d
Out[87]:
{'a': 1, 'b': 2, 'c': 3}
In [88]:
d['b']
Out[88]:
2
In [89]:
d1 = dict(d=4, e=5, f=6)
d1
Out[89]:
{'d': 4, 'e': 5, 'f': 6}
In [90]:
d.update(d1)
d
Out[90]:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
In [91]:
list(d.keys())
Out[91]:
['d', 'c', 'a', 'b', 'f', 'e']
In [92]:
list(d.values())
Out[92]:
[4, 3, 1, 2, 6, 5]
In [93]:
d['g'] = 7
d
Out[93]:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7}
In [94]:
for k in d:
    print(k, d[k])
d 4
c 3
g 7
a 1
b 2
f 6
e 5

Dictionary variants

In [95]:
d = {}
d['z'] = 1
d['x'] = 2
d['y'] = 3

for k in d:
    print(k, d[k])
z 1
x 2
y 3
In [96]:
d = collections.OrderedDict()
d['z'] = 1
d['x'] = 2
d['y'] = 3

for k in d:
    print(k, d[k])
z 1
x 2
y 3
In [97]:
d = collections.defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].extend([3,4,5])
d
Out[97]:
defaultdict(list, {'a': [1, 2], 'b': [3, 4, 5]})

Example: Word counter

In [98]:
jabberwocky = '''
’Twas brillig, and the slithy toves
      Did gyre and gimble in the wabe:
All mimsy were the borogoves,
      And the mome raths outgrabe.

“Beware the Jabberwock, my son!
      The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
      The frumious Bandersnatch!”

He took his vorpal sword in hand;
      Long time the manxome foe he sought—
So rested he by the Tumtum tree
      And stood awhile in thought.

And, as in uffish thought he stood,
      The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
      And burbled as it came!

One, two! One, two! And through and through
      The vorpal blade went snicker-snack!
He left it dead, and with its head
      He went galumphing back.

“And hast thou slain the Jabberwock?
      Come to my arms, my beamish boy!
O frabjous day! Callooh! Callay!”
      He chortled in his joy.

’Twas brillig, and the slithy toves
      Did gyre and gimble in the wabe:
All mimsy were the borogoves,
      And the mome raths outgrabe.
'''

Using regular dictionary

In [99]:
c1 = {}
for word in jabberwocky.split():
    c1[word] = c1.get(word, 0) + 1
c1['vorpal']
Out[99]:
2

Using defaultdict with int factory

In [100]:
c2 = collections.defaultdict(int)
for word in jabberwocky.split():
    c2[word] += 1
c2['vorpal']
Out[100]:
2

Using Counter

In [101]:
c3 = collections.Counter(jabberwocky.split())
c3['vorpal']
Out[101]:
2

Control Structures

if-elif-else

In [102]:
x, y = 3,4

if (x > y):
    print(x, '>', y)
elif (x == y):
    print(x, 'equals', y)
else:
    print('Either', x, '<', y, 'or x and y are not orderable')
Either 3 < 4 or x and y are not orderable

for

In [103]:
for fruit in fruits:
    print(fruit)
apple
banana
cherry
durian
eggplant
fig

while

In [104]:
i = 0
while (i < 5):
    print(i)
    i += 1
0
1
2
3
4

continue and break

In [105]:
for i in range(3):
    for j in range(5):
        if i==j:
            continue
        print(i, j)
0 1
0 2
0 3
0 4
1 0
1 2
1 3
1 4
2 0
2 1
2 3
2 4
In [106]:
i = 0
while True:
    print(i)
    if i > 5:
        break
    i += 1
0
1
2
3
4
5
6

Functions

Built-in functions

In [107]:
([x for x in dir(__builtin__)  if x.islower() and not x.startswith('__')])
Out[107]:
['abs',
 'all',
 'any',
 'ascii',
 'bin',
 'bool',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'divmod',
 'dreload',
 'enumerate',
 'eval',
 'exec',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'repr',
 'reversed',
 'round',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'vars',
 'zip']
In [108]:
len('hello')
Out[108]:
5
In [109]:
range(5, 10, 2)
Out[109]:
range(5, 10, 2)
In [110]:
ord('c') - ord('a')
Out[110]:
2
In [111]:
chr(ord('a') + 2)
Out[111]:
'c'
In [112]:
list(zip('abcd', range(1,10)))
Out[112]:
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
In [113]:
sum([4,5,6])
Out[113]:
15
In [114]:
sorted(fruits)
Out[114]:
['apple', 'banana', 'cherry', 'durian', 'eggplant', 'fig']
In [115]:
sorted(fruits, reverse=True)
Out[115]:
['fig', 'eggplant', 'durian', 'cherry', 'banana', 'apple']
In [116]:
sorted(fruits, key=len)
Out[116]:
['fig', 'apple', 'banana', 'cherry', 'durian', 'eggplant']

User-defined functions

In [117]:
def f(a, b, c):
    return a + b * c
In [118]:
f(1,2,3)
Out[118]:
7
In [119]:
f(c=3, a=1, b=2)
Out[119]:
7
In [120]:
f(1,2,c=3)
Out[120]:
7
In [121]:
args = [1,2,3]
f(*args)
Out[121]:
7
In [122]:
kwargs = dict(a=1, b=2, c=3)
f(**kwargs)
Out[122]:
7

Version Information

In [123]:
%load_ext version_information
%version_information numpy, scipy, seaborn
Out[123]:
SoftwareVersion
Python3.5.1 64bit [GCC 4.2.1 (Apple Inc. build 5577)]
IPython4.0.1
OSDarwin 15.2.0 x86_64 i386 64bit
numpy1.10.2
scipy0.16.0
seaborn0.6.0
Thu Jan 14 09:49:57 2016 EST
In [ ]: