Easiest way to install: Python distributions
Python 2 vs Python 3:
Use Python 3!
Two modes: command mode and edit mode
Command mode keyboard shortcuts:
Edit mode:
Section headings:
#
Heading 1##
Heading 2##
Heading 3**
...**
or __
...__
*
...*
or _
..._
**_
..._**
Lists:
- item 1
- item 2
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}
Read the tutorial https://docs.python.org/3/tutorial
Packages: Anaconda has package manager conda
https://conda.io/docs/
Import packages
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 100)
y = np.sin(x)
plt.plot(x, y, 'r');
17 / 3 # division returns a float
17 // 3 # floor division rounds to integer
5 ** 2 # power
Another magic command:
%rep
25
"A string"
print(
"""
String spanning
multiple lines
""",
end='')
"A" + "B" # concatenation
a = [1, 2, 3, 4, 5, 6]
a
a.append(7)
a
len(a) # length
Important: slicing
a[0]
a[1:3]
a[:2]
a[-1]
a[-2:]
a[:] # copy of a
List comprehensions
[x**2 for x in range(10)]
[x for x in [1, 2, -3, 4] if x >= 0]
Tuples are immutable lists
b = 1, 2, 3
b
empty = ()
len(empty)
single = 'a',
len(single)
Dictionary is the data structure of Python
c = {'a': 1, 'b': 2}
c
c['a']
c['d'] = 5
c
list(c.keys())
list(c.values())
'a' in c
'c' in c
{x: x**2 for x in [2, 4, 6]}
x = 5
if x > 3:
print("x > 3")
elif x > 1:
print("x > 1")
else:
print("x <= 1")
for i in range(5):
print(i)
x = 5
while x > 0:
print(x)
x -= 1
for k, v in c.items():
print("{}: {}".format(k, v))
Creating text file
f = open("myfile.txt", "w")
f.write("first line\n")
f.write("second line\n")
f.close()
with
statement
with open("myfile.txt") as f:
for line in f:
print(line, end='')
x = 1/0
try:
x = 1/0
except ZeroDivisionError:
print("Division by zero")
def f(a, b, c=1):
"""Documentation string
Function f prints it's parameters
"""
print("f:", a, b, c)
return c + 1
f(1, 2, 3)
f(1, 2)
f(1, c=4, b=2)
f.__doc__
def f2(a, *args):
print("f2:", a)
for i, x in enumerate(args):
print("{}: {}".format(i, x))
f2(1)
f2(1, 2, 3)
def f3(a, **keywords):
print("f3:", a)
for k in keywords:
print(k, "=", keywords[k])
f3(1, b=2, c=3)
def f4(a, b):
return a+1, b+1
f4(1, 2)
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)
m = MyClass("class1")
m.print()
m.add("A")
m.print()
class MyClass2(MyClass):
def add2(self, x):
self.add(x)
self.add(x)
m2 = MyClass2("class2")
m2.add2(15)
m2.print()