Introduction to Python (Part 1)¶
IPython kernel is polyglot¶
In [1]:
%%bash
echo $PATH
/opt/conda/bin:/opt/conda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
In [3]:
%load_ext rpy2.ipython
In [4]:
%%R
1:10
[1] 1 2 3 4 5 6 7 8 9 10
In [7]:
%%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 [8]:
iris.head()
Out[8]:
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 |
Operators¶
In [9]:
2 + 3
Out[9]:
5
In [10]:
2 * 3
Out[10]:
6
In [11]:
2 ** 3
Out[11]:
8
In [12]:
2 / 3
Out[12]:
0.6666666666666666
In [14]:
2 // 3
Out[14]:
0
In [15]:
7 % 2
Out[15]:
1
In [16]:
2 < 3
Out[16]:
True
In [17]:
2 <= 3
Out[17]:
True
In [18]:
2 == 3
Out[18]:
False
In [19]:
2 != 3
Out[19]:
True
In [22]:
(2 < 3) and (3 < 2)
Out[22]:
False
In [23]:
(2 < 3) or (3 < 2)
Out[23]:
True
Strings¶
In [24]:
'hello world'
Out[24]:
'hello world'
In [25]:
"hello world"
Out[25]:
'hello world'
In [26]:
'''
One
Two
Three
'''
Out[26]:
'\nOne\nTwo\nThree\n'
In [27]:
"""One
Two
Three"""
Out[27]:
'One\nTwo\nThree'
In [28]:
print("""One
Two
Three""")
One
Two
Three
In [29]:
s = 'hello world'
In [30]:
s[:3]
Out[30]:
'hel'
In [31]:
s[3:]
Out[31]:
'lo world'
In [32]:
s[-3:]
Out[32]:
'rld'
Lists¶
In [33]:
xs = [1,2,3,4,5]
In [34]:
xs
Out[34]:
[1, 2, 3, 4, 5]
In [35]:
xs[:3]
Out[35]:
[1, 2, 3]
In [36]:
xs[3:]
Out[36]:
[4, 5]
In [38]:
ys = [1,2,3,'hello world', [8,9,10]]
In [39]:
ys
Out[39]:
[1, 2, 3, 'hello world', [8, 9, 10]]
In [40]:
ys[-1][1]
Out[40]:
9
In [41]:
ys[-1][1] = 'X'
In [42]:
ys
Out[42]:
[1, 2, 3, 'hello world', [8, 'X', 10]]
Mutability and immutability¶
In [43]:
s
Out[43]:
'hello world'
In [44]:
s[2] = 'x'
TypeErrorTraceback (most recent call last)
<ipython-input-44-a3feb2c3ba3f> in <module>()
----> 1 s[2] = 'x'
TypeError: 'str' object does not support item assignment
Tuples¶
In [45]:
zs = (1,2,3,4,'hello world')
In [46]:
zs
Out[46]:
(1, 2, 3, 4, 'hello world')
In [47]:
zs[2] = 'x'
TypeErrorTraceback (most recent call last)
<ipython-input-47-9ccfac1c6e9c> in <module>()
----> 1 zs[2] = 'x'
TypeError: 'tuple' object does not support item assignment
In [48]:
zs = 1, 2, 3, 4, 'hello world'
In [49]:
zs
Out[49]:
(1, 2, 3, 4, 'hello world')
Dictionaries¶
In [53]:
a = {
'a': 1,
'b': 2,
'c': 3,
'hello world': 4,
(1,2,3): 5
}
In [51]:
a
Out[51]:
{'a': 1, 'b': 2, 'c': 3}
In [52]:
a['b']
Out[52]:
2
In [54]:
a[(1,2,3)]
Out[54]:
5
In [55]:
a['hello world']
Out[55]:
4
In [56]:
xs = [1,1,1,2,3,3,4]
In [57]:
xs
Out[57]:
[1, 1, 1, 2, 3, 3, 4]
Multiset, bag, counter¶
In [60]:
from collections import Counter
In [61]:
c = Counter(xs)
In [62]:
c
Out[62]:
Counter({1: 3, 2: 1, 3: 2, 4: 1})
Packages and the import statement¶
In [63]:
import collections
In [64]:
collections.Counter([1,1,2])
Out[64]:
Counter({1: 2, 2: 1})
In [65]:
import collections as coll
In [66]:
coll.Counter([1,1,1,2])
Out[66]:
Counter({1: 3, 2: 1})
In [67]:
import numpy as np
In [69]:
np.linspace(1, 10, 20)
Out[69]:
array([ 1. , 1.47368421, 1.94736842, 2.42105263,
2.89473684, 3.36842105, 3.84210526, 4.31578947,
4.78947368, 5.26315789, 5.73684211, 6.21052632,
6.68421053, 7.15789474, 7.63157895, 8.10526316,
8.57894737, 9.05263158, 9.52631579, 10. ])
Built-in functions¶
In [70]:
s = 'hello world'
In [71]:
len(s)
Out[71]:
11
In [72]:
len([1,2,3])
Out[72]:
3
In [73]:
len([1,2,[3,4]])
Out[73]:
3
In [74]:
ord('a')
Out[74]:
97
In [75]:
chr(97)
Out[75]:
'a'
In [76]:
for char in 'abc':
print(ord(char))
97
98
99
In [77]:
xs = [1,2,3]
n = len(xs)
for i in range(n):
print(i, xs[i])
0 1
1 2
2 3
In [80]:
range(5)
Out[80]:
range(0, 5)
In [79]:
list(range(5))
Out[79]:
[0, 1, 2, 3, 4]
String indexing¶
In [81]:
s
Out[81]:
'hello world'
In [82]:
s[3:5]
Out[82]:
'lo'
In [83]:
s[::2]
Out[83]:
'hlowrd'
In [84]:
s[1::2]
Out[84]:
'el ol'
In [85]:
s[::-1]
Out[85]:
'dlrow olleh'
In [86]:
s[::-2]
Out[86]:
'drwolh'
In [88]:
list(reversed(s))
Out[88]:
['d', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'h']
In [89]:
help(s)
No Python documentation found for 'hello world'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
String methods¶
In [90]:
s.count('o')
Out[90]:
2
In [92]:
dna = 'AATTAGAGGACCAATTT'
In [94]:
dna.count('C') + dna.count('G')
Out[94]:
5
In [95]:
s.upper()
Out[95]:
'HELLO WORLD'
In [96]:
import string
In [97]:
string.ascii_letters
Out[97]:
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
In [98]:
string.ascii_lowercase
Out[98]:
'abcdefghijklmnopqrstuvwxyz'
In [99]:
string.ascii_uppercase
Out[99]:
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
In [100]:
string.punctuation
Out[100]:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
String translation¶
In [101]:
table = str.maketrans(string.ascii_lowercase, string.ascii_uppercase)
In [102]:
s
Out[102]:
'hello world'
In [103]:
s.translate(table)
Out[103]:
'HELLO WORLD'
In [104]:
table = str.maketrans('', '', 'aeiou')
In [105]:
s.translate(table)
Out[105]:
'hll wrld'
Joining and splitting strings¶
In [106]:
s.split()
Out[106]:
['hello', 'world']
In [107]:
' '.join(s.split())
Out[107]:
'hello world'
In [108]:
'-'.join(s.split())
Out[108]:
'hello-world'
In [109]:
'+@+'.join(['one', 'two', 'three'])
Out[109]:
'one+@+two+@+three'
In [110]:
s
Out[110]:
'hello world'
Replacing, concatenation and stripping¶
In [113]:
s = s.replace('hello', 'goodbye')
In [115]:
s
Out[115]:
'goodbye world'
In [116]:
s
Out[116]:
'goodbye world'
In [117]:
s + ' tomorrow'
Out[117]:
'goodbye world tomorrow'
In [122]:
s = '\t\t' + s + '\n\n'
In [123]:
s
Out[123]:
'\t\tgoodbye world\n\n\n\n'
In [124]:
print(s)
goodbye world
In [125]:
print(s.strip())
goodbye world
Numpy arrays¶
In [126]:
import numpy as np
In [127]:
xs = np.arange(10)
In [128]:
xs
Out[128]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [129]:
xs ** 2
Out[129]:
array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
In [131]:
xs = np.reshape(xs, (2,5))
In [132]:
xs
Out[132]:
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
In [133]:
np.array([3,6,8])
Out[133]:
array([3, 6, 8])
In [134]:
xs = [1,2,3]
In [135]:
xs + 3
TypeErrorTraceback (most recent call last)
<ipython-input-135-7efca7633ad0> in <module>()
----> 1 xs + 3
TypeError: can only concatenate list (not "int") to list
In [136]:
xs = np.array([1,2,3])
In [137]:
xs + 3
Out[137]:
array([4, 5, 6])
Custom functions¶
In [139]:
def add(a, b):
"""Add stuff.
a - something that can be addded
b - something that can be added
Returns a + b
"""
ans = a + b
return ans
In [140]:
help(add)
Help on function add in module __main__:
add(a, b)
Add stuff.
a - something that can be addded
b - something that can be added
Returns a + b
In [141]:
x = 2
y = 3
add(x, y)
Out[141]:
5
In [142]:
add([1,23], [6,7,8])
Out[142]:
[1, 23, 6, 7, 8]
In [ ]: