MMSB: Mathematical Modeling in Systems Biology / Apr 30 2021
Python tutorials
Installation
Anaconda: a comprehensive Python distribution with
condapackage manager and an array of scientific python packages
Writing and running
Plain Python files *.py
Jupyter notebooks *.ipynb
Jupyterlab/ Jupiter notebook (included in Anaconda dist.)
Tutorial and reference
Variable and data types
Assignment (
=) : binding a label to an object (data) so you could use it later.Data includes boolean (True/False), numbers (integers, floating-point numbers), text strings, and more.
x = 1type(x)0.1s
Python
# String, this is a comment and the Python intepreter will ignore itgreet= "Hello" # The same as greet= 'Hello'type(greet)0.0s
Python
# print functionprint(greet, "world", x)0.4s
Python
Hello world 1
# Floatsy = 1.0type(y)0.0s
Python
# Booleantype(True)0.0s
Python
# Scientific notationz = 1e-3z0.0s
Python
Python as a (fancy) calculator
# + - * / ** % //# ----------------------------x = 4y = 3.00.0s
Python
x + y0.0s
Python
x - y0.0s
Python
x * y0.0s
Python
x / y0.0s
Python
x // y0.0s
Python
x ** y0.0s
Python
x % y0.0s
Python
a = 10a = a + 1a0.0s
Python
a = 10a *= 2a0.0s
Python
# Multiple assignmentsa, b = 11, 12print(a, b)0.3s
Python
11 12
# swapb, a = a, bprint(a, b)0.3s
Python
12 11
String operations
# Repeating stringrepetition = 10'abc' * repetition0.0s
Python
# Concat strings'a' + 'b'0.0s
Python
# f-string to insert values to a string (Python 3.6+)numofcats = 10f"I have {numofcats} cat(s)."0.0s
Python
x, y = "CAPITAL", 'smol'x.lower(), y.upper()0.0s
Python
'gmail.com'.find('.com')0.0s
Python
string = 'qwqwqwqwqw'string[2:5:2]0.0s
Python
join()
toJoin = ['This', 'is', 'a', 'string']# ' '.join(toJoin)' + '.join(toJoin)0.0s
Python
Containers
List
Tuple
Dictionary
(Set)
List
# lis = []# lis = list((2, 3, 4))# lislis = [0, 1, 2, 3]# lis.append(4)lis.extend(lis)lis.insert(0, -1)lislis.remove(1)lislis.count(0)lis0.0s
Python
lis = [[1, 1, 1], [2, 2, 2]]lis[0][0]0.0s
Python
lis = [0, 1, 2, 3, 2, 3, 5]# print(sorted(lis))# print(lis)# print(lis)# lis.sort(reverse=True)# lis.reverse()# lis# print(lis)# a = reversed(lis)for i in lis: print(i)0.3s
Python
0
1
2
3
2
3
5
Tuple
# tuple list str dict set...# (a, b) = (2, 3)# a# a = (2, 3)# a# a[1]# a = ('one', 'two')# a# a = (2, 3, 4, 5)# a# print(a, len(a))# a = tuple([1, 1])# a# a[1] = 40.0s
Python
lis = [4, 2, 1, 7, 9, 10]# print(sorted(lis).index(1))# for i in range(len(lis)):# print(i, lis[i])# for i, v in enumerate(lis):# print(i, v)# 4 in lis# for i in range(10):# if (i in lis):# print('Found', i)# lis[2:]# lis[:2]# lis[1:4:2]lis = []for i in range(10): lis.append(2 * i)lislis = [i for i in range(1, 10) if i % 2 == 0]lis# lis = [i ** 2 for i in lis]# lis0.0s
Python
lis1 = [2, 3, 4]# sum(lis1)min(lis1)# max(lis1)0.0s
Python
# shallow copylis1 = [2, 3, 4]lis2 = lis1lis1.append(5)lis2# lis1 == lis2# lis1 is lis20.0s
Python
# deep copyimport copylis1 = [2, 3, 4]lis2 = copy.deepcopy(lis1)# lis1.append(5)lis2# lis1 == lis2lis1 is lis20.0s
Python
Dictionary
d = dict()d = {}# d[1] = 'one'# d# d[2] = 'two'# dd = {'one': 1, 'two': 2}dd.update({'three': 3, 'two': 5})d0.0s
Python
# d['Three'] = 10# d# del d['three']# d# del d['Four']# print(d.get('Four', 100000000000))# d.get('Five', 'No such element')d.setdefault('Five', 5)d0.0s
Python
# for i in d:# print(i)for k, v in d.items(): print(k, v)# print(list(d.keys()))# print(d.values())# for i, j in zip([1, 2, 4], [2, 4, 6]):# print(i, j)for v, k in zip(d.values(), d.keys()): print(v, k)0.3s
Python
one 1
two 5
three 3
Five 5
1 one
5 two
3 three
5 Five
Set / Frozen Set
s = set()# type(s)s.add(1)s.add(1)# ss.add(10)ss.remove(10)s# slis = [s, s]# slis# lisset = set([10, 9], 10)# lisset0.0s
Python
geneSet = set([1, 2, 3, 6, 10])geneSet2 = set([2, 4, 6, 8, 10])geneSet & geneSet2# geneSet | geneSet2# geneSet - geneSet2geneSet.intersection(geneSet2)0.0s
Python
Logical operators and control flows
Operators:
== >= <= != < > and is not orBranching:
if...elif...elseLoops:
for,while
See also: Truth table
2 <= 30.0s
Python
2 + 2 == 50.0s
Python
'Z' > 'B'0.0s
Python
# Chaining is possible1 < 2 < 30.0s
Python
4 < 2 < 50.0s
Python
(1 > 2) and (1 < 2)0.0s
Python
not 1 > 20.0s
Python
1 > 2 or 1 < 20.0s
Python
a = 1b = 1a is b0.0s
Python
a = 1b = 1.0a == b0.0s
Python
a is b0.0s
Python
if ... else
# if else elif. Note the colon.if 3 > 5: print('Yes! It is true!')else: print('No! It is not true') print('Inside of conditional !!!!')print('Out of conditional')0.4s
Python
No! It is not true
Inside of conditional !!!!
Out of conditional
a = 2 ** 3if a % 2 == 0: print('Even')else: print('Odd')0.3s
Python
Even
score = 0print("score =", score)if score > 100 : print('What?')elif 100 >= score > 80: print('Good')elif 80 >= score > 60: print('Okay')else : print('Oops')0.3s
Python
score = 0
Oops
For loops
for i in range(2, 10): print(i, end = ' ')0.3s
Python
2 3 4 5 6 7 8 9
for i in range(10): if (i == 3): break print(i, end = ' ')0.3s
Python
0 1 2
While loops
# while loopx = 0while x < 4: print(x) x += 1 if (x == 3): break0.3s
Python
0
1
2
x = input('input a number')while True: print(x) x = input('input a number') if x == '-1': break0.2s
Python
input a number 111
111
input a number 111
111
input a number -1
Useful functions
# print / input / type conversion / random / math # print(10000)# print('Hello', 'world')# print('Hello', 'world')# print('Hello', 'world')# print('Hello', 'world')# print('Hello', 'world', sep = ' strange ')# print('Hello', end = '\t')print('world', end = '\t')# print(end = '\n')print('world')0.3s
Python
world world
type(a)# type(10)# int(a) + int (b)0.0s
Python
# bool(0)# bool(1)# int(True)int(False)0.0s
Python
# float(10)int(10.9)0.0s
Python
import random0.0s
Python
random.random()0.1s
Python
random.randint(0, 100)0.0s
Python
random.uniform(0, 100)0.0s
Python
random.randrange(0, 101, 2)0.0s
Python
random.choice(['one', 'two', 'three'])# random.sample((0, 1, 2), 2)0.0s
Python
import math0.0s
Python
math.ceil(9.1)0.0s
Python
math.floor(9.1)0.0s
Python
10 ** 0.50.0s
Python
math.log(10)0.0s
Python
math.log10(10)0.0s
Python
math.exp(1)0.0s
Python
math.pi0.0s
Python
math.sin(math.pi / 2)0.0s
Python
math.cos(math.pi / 2)0.0s
Python
math.sqrt(10)0.0s
Python
File operations
open()with ... asblock