Some of the topics explained in http://docs.g-vo.org/kurse/prog1 ************ Zen of python *************** ************* import this **************** Comments: # comment -- but: usually function docstring preferred. PEP8 style: a_variable_name, a_function_name, AClassName, lines shorter than 80 characters Assignment: a = 40 -- python variables are *references*! Numeric types: int, float, complex [Attention: integer division, python2 vs. python3; "safe" integer division: 2//3 vs. 2/float(3)] Strings: str (', ", """, ''') raw strings (\n is a newline) r"windows\path"=="windows\\path". Immutable! Meaning: s.strip() does nothing. Instead, to s = s.strip() Instead of s[3] = "a", use methods like replace or slicing: s = s[:2]+"a"+s[3:] (but fiddling with chars is usually a sign you're doing it wrong). More methods: split, replace, ... use s. String formatting: template.format(args) "{foo:02d} and {bar:20.10f} or {bar:g}".format(foo=4, bar=2.5) "this {} emergency".format("is an") Lists: [a, b, c], mutable, inhomogeneous. Main method: append. len(l); indexing: l[0]...l[len(l)-1]. Also: negative indices count from back: l[-1], l[-2]... Booleans: True/False, operators: and, or, not; result, e.g., from comparisons, ==, !=, <, >, <=, >= Tuples: Like lists, just immutable. Automatic packing/unpacking: def get_coords(): return 1, 2 x, y = get_coords() Dicts! d = {'a': 3, 'b': 5}; indexing: d['a']; d.keys(), d.values(). But: not order! Use "in" operator: "a" in d. Type conversion: Just type_name(x), e.g., int(x), float(x)..., list(x) Operators: As usual: +, -, *, /, **, % (remainder). But "+" on sequences is concatenation. [gag: int*seq is seq+...+seq]. [len works for all sequences: strings, too] Slicing: seq[a:b] grabs items seq[a]...seq[b-1], str remains str, list remains list. l[:] copies l. Inspection of things in python: * type(x) gives you type * id(x) gives you "identity" * dir(x) gives you name in x's namespace Selection: if a=b: pass elif a fill arguments from sequence my_func(**kwargs) -> fill arguments from dictionary Selected built-in functions: all the type names, sum, open, len, Files: Essentially a pipeline you either put characters to or get characters from. with open("path_to/file.name", "r") as f: f.readline() f.read() for line in f: pass [with: automatically closes file when done. "maintain external invariants"] Writing: with open("new_file", "w") as f: # careful: nukes new_file f.write(stuff) Modules: import modname Access objects from modules with modname.name Built-in modules we've encountered: math, os, glob, [sys, re] Use something often: from math import sin, cos Nested modules: from matplotlib import pyplot as plt How to find useful python modules? -> synaptic, https://pypi.python.org/pypi Numpy: import numpy as np a = np.array(seq) -> array *if* seq is homogeneous a.dtype (np.int8... np.int64; np.float32... np.float96) a.shape (tuple of axis lengths) a.ndim (len(a.shape)) np.arange [like range(start, end, step)] np.linspace(start, end, steps) np.logspace(logstart, logend, steps) np.zeros -- np.empty is probably not what you want np.ones +, -, *, /, **, %, ... work element wise [actual vector/matrix products in np.linalg] With n-dim arrays, you get more slices: a = np.zeros((200,300)) b = np.ones((200,300)) a[:,3:5] Masking: a<3 is an array! Use it to select/set matching elements a[a<3] = 0 b[a<3] = 50 Plotting: for matplotlib import pyplot as plt [use --matplotlib option to ipython, %matplotlib inline in the notebook] plt.plot(x, y, marker='o', color='green', linewidth=2) Lots of other plots: scatter, hist, polar... Customise with xlabel, ylable, xlim, ylim... save: plt.savefig('my_plot.pdf') Visual help discovery: http://matplotlib.org/gallery.html Fitting data: from scipy.optimize import curve_fit def line(x, a, b): # that's my model ... popt, pcov = curve_fit(line, x, y) Numerical Integration: from scipy import integrate integrate.quad(closed_function, lower, upper) integrate.simp(func_values, x=x) Debugging: Set a breakpoint in code using import pdb; pdb.set_trace() # read pdb docs to figure out what to do (or import ipdb; ipdb.set_trace()) Raising Exceptions raise Exception("this needs to be expressive") Exception can also be ValueError, TypeError... class MyError(Exception): pass Pull things off the web: import requests resp = requests.get("http://foo.bar/baz") print resp.text [or resp.content if non-binary] also check resp.status_code (==200 if all is fine) [and see http://ivoa.net for lots of online stuff in astronomy] Defining classes: class MyClass(object): def __init__(self, arg1, arg2): self.attr1, self.attr2 = arg1, arg2 def mash_it(self, something): return something+self.attr1+self.attr2 class DerivedClass(MyClass): ...