Introduction to Python

Resources

Jupyter

Conda

Unix shell

Python

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 seaborn plotting library and setting defaults
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 suppress printing of return value for sns.barplot()
pass


Hello, world


In [3]:
print("Hello, world!")


Hello, world!

Types


In [4]:
# Boolean

True, False


Out[4]:
(True, False)

In [5]:
# Integer
0, 1, 23, int(3.8)


Out[5]:
(0, 1, 23, 3)

In [6]:
# Float
1.2, 3.14, float(2)


Out[6]:
(1.2, 3.14, 2.0)

In [7]:
# Complex
1 + 2j, complex(23)


Out[7]:
((1+2j), (23+0j))

In [8]:
# String
('abc', "abc", 
"""abc
def
ghi""",
r'\t')


Out[8]:
('abc', 'abc', 'abc\ndef\nghi', '\\t')

In [9]:
# None
None

In [10]:
type(3)


Out[10]:
int

In [11]:
type(poisson_pmf)


Out[11]:
function

Operators


In [12]:
2 * 3


Out[12]:
6

In [13]:
2 ** 3


Out[13]:
8

In [14]:
2 ^ 3 # danger, Will Robinson! ^ is bitwise exclusive-or, not exponentiation


Out[14]:
1

In [15]:
7 /3


Out[15]:
2.3333333333333335

In [16]:
7 // 3


Out[16]:
2

In [17]:
2 < 3


Out[17]:
True

In [18]:
7 % 3


Out[18]:
1

In [19]:
1 == 1


Out[19]:
True

In [20]:
1 != 2


Out[20]:
True

In [21]:
a = [1,2,3]
b = a
c = [1,2,3]

In [22]:
b == a


Out[22]:
True

In [23]:
b is a


Out[23]:
True

In [24]:
c == a


Out[24]:
True

In [25]:
c is a


Out[25]:
False

In [26]:
np.array([1,2,3]) @ np.array([1,2,3])


Out[26]:
14

In [27]:
True or False, True | False


Out[27]:
(True, True)

In [28]:
True and False, False & True


Out[28]:
(False, False)

In [29]:
2 << 4


Out[29]:
32

In [30]:
fruits = ['apple', 'banana', 'cherry', 'durian', 'eggplant', 'fig']
'durian' in fruits


Out[30]:
True

The operator module

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


In [31]:
import operator as op

op.mul(3, 4)


Out[31]:
12

In [32]:
from functools import reduce

reduce(op.mul, [2,3,4,5], 1)


Out[32]:
120

Names, assignment and identity


In [33]:
# Create some object (the list [1,2,3]) on the RHS and assign it to the name on the LHS

In [34]:
a = [1,2,3]

In [35]:
a


Out[35]:
[1, 2, 3]

In [36]:
# Find the identity (address in memory in CPython) of the object named a

In [37]:
id(a)


Out[37]:
4439213064

In [38]:
# Give the object named as a another name b

In [39]:
b = a

In [40]:
b


Out[40]:
[1, 2, 3]

In [41]:
# b is just another name for the object also named a
# So the identity is the same
id(b)


Out[41]:
4439213064

In [42]:
# Create a new object (the list [1,23]) and give it a name c

In [43]:
c = [1,2,3]

In [44]:
c


Out[44]:
[1, 2, 3]

In [45]:
# The object named c has a different identity from the object with names a, b
id(c)


Out[45]:
4684024264

In [46]:
a


Out[46]:
[1, 2, 3]

In [47]:
b[0] = 99

In [48]:
a


Out[48]:
[99, 2, 3]

In [49]:
c


Out[49]:
[1, 2, 3]

Augmented assignment


In [50]:
x = 1

In [51]:
x += 2
x


Out[51]:
3

In [52]:
x **= 3
x


Out[52]:
27

Naming conventions

Collections

Tuples


In [53]:
course = ('STA-663', 2017, 'Spring', 50)

In [54]:
course[0]


Out[54]:
'STA-663'

In [55]:
course[1]


Out[55]:
2017

In [56]:
course[-1]


Out[56]:
50

Tuple unpacking


In [57]:
name, year, semester, size = course

In [58]:
semester


Out[58]:
'Spring'

In [59]:
name, *when, size = course

In [60]:
name


Out[60]:
'STA-663'

In [61]:
size


Out[61]:
50

In [62]:
when


Out[62]:
[2017, 'Spring']

Named tuples


In [63]:
import collections

In [64]:
course = collections.namedtuple('course', ['name', 'year','semester', 'size'])

In [65]:
sta_663 = course(name = 'STA-663', year=2017, size=50, semester='Spring')

In [66]:
sta_663


Out[66]:
course(name='STA-663', year=2017, semester='Spring', size=50)

In [67]:
name, *when, size = sta_663

In [68]:
when


Out[68]:
[2017, 'Spring']

In [69]:
sta_663[-1]


Out[69]:
50

In [70]:
sta_663.size


Out[70]:
50

Lists


In [71]:
x = [1,2,3,4,5]

In [72]:
x[1:4]


Out[72]:
[2, 3, 4]

In [73]:
x[-1] = 10
x


Out[73]:
[1, 2, 3, 4, 10]

In [74]:
x[::2]


Out[74]:
[1, 3, 10]

In [75]:
x[::-1]


Out[75]:
[10, 4, 3, 2, 1]

In [76]:
x + x


Out[76]:
[1, 2, 3, 4, 10, 1, 2, 3, 4, 10]

In [77]:
x * 3


Out[77]:
[1, 2, 3, 4, 10, 1, 2, 3, 4, 10, 1, 2, 3, 4, 10]

In [78]:
x.append(20)
x


Out[78]:
[1, 2, 3, 4, 10, 20]

In [79]:
x.extend([3,4,5])
x


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

In [80]:
x.index(10)


Out[80]:
4

In [81]:
x.count(3)


Out[81]:
2

Sets


In [82]:
s = {1,1,2,3,4}
s


Out[82]:
{1, 2, 3, 4}

In [83]:
s.add(2)
s


Out[83]:
{1, 2, 3, 4}

In [84]:
s.add(5)
s


Out[84]:
{1, 2, 3, 4, 5}

Set operations and equivalent methods


In [85]:
s & {5,6,7}, s.intersection({5,6,7})


Out[85]:
({5}, {5})

In [86]:
s | {5,6,7}, s.union({5,6,7})


Out[86]:
({1, 2, 3, 4, 5, 6, 7}, {1, 2, 3, 4, 5, 6, 7})

In [87]:
s - {5,6,7}, s.difference({5,6,7})


Out[87]:
({1, 2, 3, 4}, {1, 2, 3, 4})

In [88]:
s ^ {5,6,7}, s.symmetric_difference({5,6,7})


Out[88]:
({1, 2, 3, 4, 6, 7}, {1, 2, 3, 4, 6, 7})

Dictionary


In [89]:
d = {'a': 1, 'b':2, 'c':3}
d


Out[89]:
{'a': 1, 'b': 2, 'c': 3}

In [90]:
d['b']


Out[90]:
2

In [91]:
d1 = dict(d=4, e=5, f=6)
d1


Out[91]:
{'d': 4, 'e': 5, 'f': 6}

In [92]:
d.update(d1)
d


Out[92]:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

In [93]:
list(d.keys())


Out[93]:
['c', 'e', 'a', 'd', 'f', 'b']

In [94]:
list(d.values())


Out[94]:
[3, 5, 1, 4, 6, 2]

In [95]:
d['g'] = 7
d


Out[95]:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7}

In [96]:
for k in d:
    print(k, d[k])


c 3
e 5
a 1
g 7
d 4
f 6
b 2

Dictionary variants


In [97]:
# From Python 3.6 regular dictionaries will maintain order

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

for k in d:
    print(k, d[k])


x 2
y 3
z 1

In [98]:
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 [99]:
d = collections.defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].extend([3,4,5])
d


Out[99]:
defaultdict(list, {'a': [1, 2], 'b': [3, 4, 5]})

Example: Word counter


In [100]:
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 [101]:
c1 = {}
for word in jabberwocky.split():
    c1[word] = c1.get(word, 0) + 1
c1['vorpal']


Out[101]:
2

Using defaultdict with int factory


In [102]:
int() # Note int is a factory fucntion that produces 0


Out[102]:
0

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


Out[103]:
2

Using Counter


In [104]:
c3 = collections.Counter(jabberwocky.split())
c3['vorpal']


Out[104]:
2

Control Structures

if-elif-else


In [105]:
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 [106]:
for fruit in fruits:
    print(fruit)


apple
banana
cherry
durian
eggplant
fig

while


In [107]:
i = 0
while (i < 5):
    print(i)
    i += 1


0
1
2
3
4

continue and break


In [108]:
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 [109]:
i = 0
while True:
    print(i)
    if i > 5:
        break
    i += 1


0
1
2
3
4
5
6

Functions

Built-in functions


In [110]:
([x for x in dir(__builtin__)  if x.islower() and not x.startswith('__')])


Out[110]:
['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 [111]:
len('hello')


Out[111]:
5

In [112]:
range(5, 10, 2)


Out[112]:
range(5, 10, 2)

In [113]:
ord('c') - ord('a')


Out[113]:
2

In [114]:
chr(ord('a') + 2)


Out[114]:
'c'

In [115]:
list(zip('abcd', range(1,10)))


Out[115]:
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

In [116]:
sum([4,5,6])


Out[116]:
15

In [117]:
sorted(fruits)


Out[117]:
['apple', 'banana', 'cherry', 'durian', 'eggplant', 'fig']

In [118]:
sorted(fruits, reverse=True)


Out[118]:
['fig', 'eggplant', 'durian', 'cherry', 'banana', 'apple']

In [119]:
sorted(fruits, key=len)


Out[119]:
['fig', 'apple', 'banana', 'cherry', 'durian', 'eggplant']

User-defined functions


In [120]:
def f(a, b, c):
    return a + b * c

In [121]:
f(1,2,3)


Out[121]:
7

In [122]:
f(c=3, a=1, b=2)


Out[122]:
7

In [123]:
f(1,2,c=3)


Out[123]:
7

In [124]:
args = [1,2,3]
f(*args)


Out[124]:
7

In [125]:
kwargs = dict(a=1, b=2, c=3)
f(**kwargs)


Out[125]:
7