Getting started with Python

Installation

Easiest way to install: Python distributions

Python 2 vs Python 3:
Use Python 3!

Cloud services

Jupyter interface

Two modes: command mode and edit mode

Command mode keyboard shortcuts:

  • a : insert cell above
  • b : insert cell below
  • dd : delete selected cell
  • m : markdown
  • Enter: edit mode

Edit mode:

  • Tab : code completion or indent
  • Shift + Tab : tooltip
  • Esc : command mode

Markdown

Section headings:

  • # Heading 1
  • ## Heading 2
  • ## Heading 3
  • bold : **...** or __...__
  • italic : *...* or _..._
  • bold and italic : **_..._**

Lists:

  • unordered
- item 1
- item 2
  • ordered
1. item 1
2. item 2

MathJax https://www.mathjax.org/

$X_i^j$, see $$ a = \sum_i b_i \int_c^d f(x)\,\mathrm{d}x $$

$...$ for inline math, $$...$$ for displayed math

\begin{align} \dot{x} & = \sigma(y-x) \\ \dot{y} & = \rho x - y - xz \\ \dot{z} & = -\beta z + xy \end{align}

Python

Packages: Anaconda has package manager conda https://conda.io/docs/

Import packages

In [1]:
import numpy as np

%matplotlib inline
import matplotlib.pyplot as plt
In [6]:
x = np.linspace(0, 20, 100)
y = np.sin(x)
plt.plot(x, y, 'r');

Operators

In [9]:
17 / 3  # division returns a float
Out[9]:
5.666666666666667
In [12]:
17 // 3  # floor division rounds to integer
Out[12]:
5
In [13]:
 5 ** 2  # power
Out[13]:
25

Another magic command:

In [14]:
%rep
In [ ]:
25

Strings

In [7]:
"A string"
Out[7]:
'A string'
In [8]:
print(
"""
String spanning
multiple lines
""",
end='')
String spanning
multiple lines
In [15]:
"A" + "B" # concatenation
Out[15]:
'AB'

Lists

In [24]:
a = [1, 2, 3, 4, 5, 6]
a
Out[24]:
[1, 2, 3, 4, 5, 6]
In [26]:
a.append(7)
a
Out[26]:
[1, 2, 3, 4, 5, 6, 7]
In [36]:
len(a) # length
Out[36]:
7

Important: slicing

In [27]:
a[0]
Out[27]:
1
In [28]:
a[1:3]
Out[28]:
[2, 3]
In [29]:
a[:2]
Out[29]:
[1, 2]
In [30]:
a[-1]
Out[30]:
7
In [33]:
a[-2:]
Out[33]:
[6, 7]
In [34]:
a[:] # copy of a
Out[34]:
[1, 2, 3, 4, 5, 6, 7]

List comprehensions

In [37]:
[x**2 for x in range(10)]
Out[37]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [38]:
[x for x in [1, 2, -3, 4] if x >= 0]
Out[38]:
[1, 2, 4]

Tuples

Tuples are immutable lists

In [39]:
b = 1, 2, 3
b
Out[39]:
(1, 2, 3)
In [40]:
empty = ()
len(empty)
Out[40]:
0
In [41]:
single = 'a',
len(single)
Out[41]:
1

Dictionaries

Dictionary is the data structure of Python

In [43]:
c = {'a': 1, 'b': 2}
c
Out[43]:
{'a': 1, 'b': 2}
In [44]:
c['a']
Out[44]:
1
In [45]:
c['d'] = 5
c
Out[45]:
{'a': 1, 'b': 2, 'd': 5}
In [46]:
list(c.keys())
Out[46]:
['a', 'b', 'd']
In [47]:
list(c.values())
Out[47]:
[1, 2, 5]
In [48]:
'a' in c
Out[48]:
True
In [49]:
'c' in c
Out[49]:
False
In [51]:
{x: x**2 for x in [2, 4, 6]}
Out[51]:
{2: 4, 4: 16, 6: 36}

Control flow

In [54]:
x = 5
if x > 3:
    print("x > 3")
elif x > 1:
    print("x > 1")
else:
    print("x <= 1")
x > 3
In [56]:
for i in range(5):
    print(i)
0
1
2
3
4
In [57]:
x = 5
while x > 0:
    print(x)
    x -= 1
5
4
3
2
1
In [61]:
for k, v in c.items():
    print("{}: {}".format(k, v))
a: 1
b: 2
d: 5

Creating text file

In [62]:
f = open("myfile.txt", "w")
f.write("first line\n")
f.write("second line\n")
f.close()

with statement

In [64]:
with open("myfile.txt") as f:
    for line in f:
        print(line, end='')
first line
second line

Exceptions

In [68]:
x = 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-68-bfdf2b0f658a> in <module>()
----> 1 x = 1/0

ZeroDivisionError: division by zero
In [69]:
try:
    x = 1/0
except ZeroDivisionError:
    print("Division by zero")
Division by zero

Functions

In [70]:
def f(a, b, c=1):
    """Documentation string
    Function f prints it's parameters
    """
    print("f:", a, b, c)
    return c + 1
In [71]:
f(1, 2, 3)
f: 1 2 3
Out[71]:
4
In [72]:
f(1, 2)
f: 1 2 1
Out[72]:
2
In [74]:
f(1, c=4, b=2)
f: 1 2 4
Out[74]:
5
In [75]:
f.__doc__
Out[75]:
"Documentation string\n    Function f prints it's parameters\n    "
In [76]:
def f2(a, *args):
    print("f2:", a)
    for i, x in enumerate(args):
        print("{}: {}".format(i, x))
In [77]:
f2(1)
f2: 1
In [78]:
f2(1, 2, 3)
f2: 1
0: 2
1: 3
In [79]:
def f3(a, **keywords):
    print("f3:", a)
    for k in keywords:
        print(k, "=", keywords[k])
In [80]:
f3(1, b=2, c=3)
f3: 1
b = 2
c = 3
In [87]:
def f4(a, b):
    return a+1, b+1
In [88]:
f4(1, 2)
Out[88]:
(2, 3)

Classes

In [89]:
class MyClass:
    def __init__(self, name):
        self.name = name
        self.data = []
    
    def add(self, x):
        self.data.append(x)
    
    def print(self):
        print(self.name, ": ", self.data)
In [90]:
m = MyClass("class1")
In [91]:
m.print()
class1 :  []
In [92]:
m.add("A")
In [93]:
m.print()
class1 :  ['A']
In [94]:
class MyClass2(MyClass):
    def add2(self, x):
        self.add(x)
        self.add(x)
In [95]:
m2 = MyClass2("class2")
In [96]:
m2.add2(15)
In [97]:
m2.print()
class2 :  [15, 15]