Getting started with Jupyter and Python

The Jupyter notebook

Code cells

In [1]:
1 + 1 == 2
Out[1]:
True

Markdown cells

Headings are indicated by #, ##, ###, or ####.

  • list
  • of
  • stuff

Some LaTeX

\(\alpha \beta \gamma\)

Creating, deleting and moving cells

In [ ]:
here

Getting help

In [5]:
range?

Magic functions

In [11]:
%%bash

echo "Hello world"

Hello world

Python Basics

Comments

In [13]:
# this is a comment
1 + 1 == 2 # my new math theorem
Out[13]:
True

Basic data types

numbers, strings, booleans, None

In [14]:
2
Out[14]:
2
In [15]:
3.14
Out[15]:
3.14
In [16]:
4 + 3j
Out[16]:
(4+3j)
In [17]:
'hello, world'
Out[17]:
'hello, world'
In [19]:
"hello's world"
Out[19]:
"hello's world"
In [20]:
'''This
is a
multi-line
string'''
Out[20]:
'This\nis a \nmulti-line\nstring'
In [ ]:
True, False
In [21]:
None

Operators

arithmetic, logical, relational, bitwise, ternary

In [23]:
1 + 2, 1 - 2, 1 * 2,
Out[23]:
(3, -1, 2)
In [24]:
2**3
Out[24]:
8
In [25]:
2/3
Out[25]:
0.6666666666666666
In [26]:
2 // 3
Out[26]:
0
In [28]:
7 % 2 == 0
Out[28]:
False
In [29]:
2 < 3
Out[29]:
True
In [30]:
2 >= 3
Out[30]:
False
In [32]:
2 == 3, 2 != 3
Out[32]:
(False, True)
In [37]:
(1 > 2) or (2 > 1)
Out[37]:
True
In [34]:
(1 > 2) and (2 > 1)
Out[34]:
False
In [35]:
not (1 > 2) and (2 > 1)
Out[35]:
True
In [40]:
7 & 3
Out[40]:
3

Collections

list, tuple, set, dict

In [42]:
xs = [1,2,3,4,5]
In [43]:
xs
Out[43]:
[1, 2, 3, 4, 5]
In [44]:
xs[0]
Out[44]:
1
In [53]:
xs[:-1]
Out[53]:
[1, 2, 3, 4]
In [54]:
xs[::-1]
Out[54]:
[5, 4, 3, 2, 1]
In [55]:
xs.append(6)
In [56]:
xs
Out[56]:
[1, 2, 3, 4, 5, 6]
In [57]:
xs.extend([7,8,9])
In [58]:
xs
Out[58]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [59]:
[1,2] + [3,4]
Out[59]:
[1, 2, 3, 4]
In [60]:
[1,2] * 3
Out[60]:
[1, 2, 1, 2, 1, 2]
In [62]:
xs.clear()
In [63]:
xs
Out[63]:
[]
In [65]:
(1,1,2,3,5,8)
Out[65]:
(1, 1, 2, 3, 5, 8)
In [66]:
xs = [1,2,3]
In [67]:
ys = (1,2,3)
In [68]:
xs[1] *= 9
In [69]:
xs
Out[69]:
[1, 18, 3]
In [70]:
ys[1] *= 9

TypeErrorTraceback (most recent call last)
<ipython-input-70-b9a74fac84ed> in <module>()
----> 1 ys[1] *= 9

TypeError: 'tuple' object does not support item assignment
In [71]:
('tom', 'price', 23, '%500,000')
Out[71]:
('tom', 'price', 23, '%500,000')
In [72]:
set([1,1,2,3,4,1,2,3])
Out[72]:
{1, 2, 3, 4}
In [73]:
from collections import Counter
In [74]:
c = Counter([1,1,2,3,4,1,2,3])
In [75]:
c
Out[75]:
Counter({1: 3, 2: 2, 3: 2, 4: 1})
In [77]:
c[3]
Out[77]:
2
In [78]:
d = {'a': 1, 'b': 2}
In [79]:
d
Out[79]:
{'a': 1, 'b': 2}
In [80]:
d['a']
Out[80]:
1
In [81]:
dict(a = 2, b=3)
Out[81]:
{'a': 2, 'b': 3}

Indexing and slicing

zero-indexing, start, stop, stride

In [3]:
xs = list(range(10))
In [4]:
xs
Out[4]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [5]:
xs[0]
Out[5]:
0
In [6]:
xs[2:5]
Out[6]:
[2, 3, 4]
In [7]:
xs[2:9:2]
Out[7]:
[2, 4, 6, 8]
In [8]:
xs[:3]
Out[8]:
[0, 1, 2]
In [9]:
xs[3:]
Out[9]:
[3, 4, 5, 6, 7, 8, 9]
In [10]:
xs[-1]
Out[10]:
9
In [11]:
xs[-3:]
Out[11]:
[7, 8, 9]
In [12]:
xs[::-1]
Out[12]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [13]:
list(reversed(xs))
Out[13]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Looping

for, while

In [14]:
for i in range(5):
    print(i, i**2)
0 0
1 1
2 4
3 9
4 16
In [15]:
for i in [2,5,9]:
    print(i)
2
5
9
In [16]:
for i, x in enumerate([2,5,9]):
    print(i, x)
0 2
1 5
2 9
In [17]:
for i, x in enumerate([2,5,9], start=1):
    print(i, x)
1 2
2 5
3 9
In [18]:
i = 0
while i < 5:
    i += 1
    print(i)
1
2
3
4
5
In [19]:
i = 0
while True:
    i += 1
    print(i)
    if i > 5:
        break
1
2
3
4
5
6
In [20]:
i = 0
while 'not very true':
    i += 1
    print(i)
    if i > 5:
        break
1
2
3
4
5
6

Cotnrol flow

if-elif-else, continue, break, pass

In [23]:
for i in range(1, 101):
    if i > 50:
        break
    if i % 3 == 0:
        continue

    if (i % 3 == 0) & (i % 5 == 0):
        print("FizzBuzz", end=',')
    elif (i % 3 == 0):
        print("Fizz", end=',')
    elif (i % 5 == 0):
        print("Buzz", end=',')
    else:
        print(i, end=',')
1,2,4,Buzz,7,8,Buzz,11,13,14,16,17,19,Buzz,22,23,Buzz,26,28,29,31,32,34,Buzz,37,38,Buzz,41,43,44,46,47,49,Buzz,

List, set, dictionary comprehensions

comprehensions, if, nested comprehensions

In [25]:
xs = []
for i in range(10):
    if i % 2 == 0:
        xs.append(i**2)
xs
Out[25]:
[0, 4, 16, 36, 64]
In [26]:
[i**2 for i in range(10) if i % 2 == 0]
Out[26]:
[0, 4, 16, 36, 64]
In [36]:
xs = []
for i in range(3):
    for j in range(4):
        xs.append((i,j))
        if j == 1:
            break
print(xs)
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
In [29]:
print([(i,j) for i in range(3) for j in range(4)])
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
In [ ]:
[i**2 for i in range(10**400)]
In [33]:
gen = (i**2 for i in range(10**400))
In [34]:
for i in gen:
    print(i)
    if i > 1000:
        break
0
1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
400
441
484
529
576
625
676
729
784
841
900
961
1024

Generator expressions

laziness, iterators, iter, next, StopIteration

In [37]:
(i for i in range(10) if i % 3 == 0)
Out[37]:
<generator object <genexpr> at 0x7f5876b890f8>
In [38]:
{i for i in [1,1,2,3,4,3]}
Out[38]:
{1, 2, 3, 4}
In [39]:
{s: len(s) for s in ['apple', 'pear', 'bababa']}
Out[39]:
{'apple': 5, 'bababa': 6, 'pear': 4}

Built-in functions

sum, range, enumerate, sorted, reversed

In [40]:
sum(range(10))
Out[40]:
45
In [42]:
sorted([3,1,5,2,4])
Out[42]:
[1, 2, 3, 4, 5]
In [43]:
reversed([3,1,5,2,4])
Out[43]:
<list_reverseiterator at 0x7f5876baf710>
In [46]:
sum(range(5), 10)
Out[46]:
20

Standard libraries

string, math, random

In [47]:
import string
In [48]:
string.ascii_lowercase
Out[48]:
'abcdefghijklmnopqrstuvwxyz'
In [49]:
string.ascii_uppercase
Out[49]:
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
In [50]:
string.punctuation
Out[50]:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
In [51]:
from string import punctuation, ascii_letters
In [52]:
punctuation
Out[52]:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
In [53]:
ascii_letters
Out[53]:
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
In [54]:
import string as ss
In [55]:
ss.digits
Out[55]:
'0123456789'
In [56]:
import math
In [57]:
math.sqrt(2)
Out[57]:
1.4142135623730951
In [58]:
import random
In [59]:
random.uniform(0, 5)
Out[59]:
4.254708589608265

I/O

reading and writing text files, context managers

In [61]:
%%file mary.txt

mary had a little lamb
little lamb
little lamb
its fleece was white as snow
Writing mary.txt
In [65]:
with open('mary.txt') as f:
    for line in f:
        if not line.startswith('#'):
            print(line.strip())

mary had a little lamb
little lamb
little lamb
its fleece was white as snow
In [66]:
with open('mary.txt') as f:
    text = f.read()
In [67]:
text
Out[67]:
'\nmary had a little lamb\nlittle lamb\nlittle lamb\nits fleece was white as snow'
In [68]:
with open('mary.txt') as f:
    text = f.readlines()
In [69]:
text
Out[69]:
['\n',
 'mary had a little lamb\n',
 'little lamb\n',
 'little lamb\n',
 'its fleece was white as snow']

Polyglot programming

Using bash and R together with Python

In [70]:
%load_ext rpy2.ipython
In [71]:
x = %R 1:3
In [72]:
x
Out[72]:
array([1, 2, 3], dtype=int32)
In [75]:
%%R -o iris
head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

In [76]:
iris
Out[76]:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
7 4.6 3.4 1.4 0.3 setosa
8 5.0 3.4 1.5 0.2 setosa
9 4.4 2.9 1.4 0.2 setosa
10 4.9 3.1 1.5 0.1 setosa
11 5.4 3.7 1.5 0.2 setosa
12 4.8 3.4 1.6 0.2 setosa
13 4.8 3.0 1.4 0.1 setosa
14 4.3 3.0 1.1 0.1 setosa
15 5.8 4.0 1.2 0.2 setosa
16 5.7 4.4 1.5 0.4 setosa
17 5.4 3.9 1.3 0.4 setosa
18 5.1 3.5 1.4 0.3 setosa
19 5.7 3.8 1.7 0.3 setosa
20 5.1 3.8 1.5 0.3 setosa
21 5.4 3.4 1.7 0.2 setosa
22 5.1 3.7 1.5 0.4 setosa
23 4.6 3.6 1.0 0.2 setosa
24 5.1 3.3 1.7 0.5 setosa
25 4.8 3.4 1.9 0.2 setosa
26 5.0 3.0 1.6 0.2 setosa
27 5.0 3.4 1.6 0.4 setosa
28 5.2 3.5 1.5 0.2 setosa
29 5.2 3.4 1.4 0.2 setosa
30 4.7 3.2 1.6 0.2 setosa
... ... ... ... ... ...
121 6.9 3.2 5.7 2.3 virginica
122 5.6 2.8 4.9 2.0 virginica
123 7.7 2.8 6.7 2.0 virginica
124 6.3 2.7 4.9 1.8 virginica
125 6.7 3.3 5.7 2.1 virginica
126 7.2 3.2 6.0 1.8 virginica
127 6.2 2.8 4.8 1.8 virginica
128 6.1 3.0 4.9 1.8 virginica
129 6.4 2.8 5.6 2.1 virginica
130 7.2 3.0 5.8 1.6 virginica
131 7.4 2.8 6.1 1.9 virginica
132 7.9 3.8 6.4 2.0 virginica
133 6.4 2.8 5.6 2.2 virginica
134 6.3 2.8 5.1 1.5 virginica
135 6.1 2.6 5.6 1.4 virginica
136 7.7 3.0 6.1 2.3 virginica
137 6.3 3.4 5.6 2.4 virginica
138 6.4 3.1 5.5 1.8 virginica
139 6.0 3.0 4.8 1.8 virginica
140 6.9 3.1 5.4 2.1 virginica
141 6.7 3.1 5.6 2.4 virginica
142 6.9 3.1 5.1 2.3 virginica
143 5.8 2.7 5.1 1.9 virginica
144 6.8 3.2 5.9 2.3 virginica
145 6.7 3.3 5.7 2.5 virginica
146 6.7 3.0 5.2 2.3 virginica
147 6.3 2.5 5.0 1.9 virginica
148 6.5 3.0 5.2 2.0 virginica
149 6.2 3.4 5.4 2.3 virginica
150 5.9 3.0 5.1 1.8 virginica

150 rows × 5 columns