#acl AdminGroup:read,write,delete,revert EditorGroup:read All:read #format wiki #language en #pragma section-numbers off <> = Variable names = Allowed names for identifier (name of variable or function): * Any sequence of alphabetical character, number, or underline character {{{_}}} * First symbol has to be a character * Case sensitive * Not a python built-in keyword == Name space == The Python interpreter maps the name of an identifier in the active name space. The active name space depends on the active code block (module, function). The identifier can be local or global with respect to the active code block. {{{#!python def func(a): a=a+1 # a is visibly only within func() print a b=func(1) print b print a # This will throw a NameError exception }}} {{{#!python import scipy scipy.pi # pi is in the name space of scipy from scipy import pi pi # pi is in the active name space from scipy import * pi # all identifiers of scipy are in the active name space del(pi) # Deletes pi from the active name space reset # ipython function to delete all identifiers }}} = Built-in datatypes = == Scalar == * Plain integer: {{{9}}} * Long integer: {{{9**99, 1L}}} * Hex integer: {{{0x10}}} * Floating point: {{{0.1}}} * Exponential floating point: {{{1e-3}}} * Complex: {{{3+2j}}} === Casting === * int() * long() * float() * complex() * str() == Sequences == === String === {{{#!python s1='Hello world' s2="Hello world" s1==s2 s='"' s="'" }}} == Dictionary == {{{#!python D={1:'one',2:'two','one':1,'two':2} D['one'] D[1] }}} = Extended data types = == Array == NumPy/SciPy provides a multidimensional '''array''' data type. An array can hold arbitrary Python objects but usually they are used for N-dimensional numeric data types. === Array creation === * {{{empty((d1,d2),dtype)}}} returns uninitialized array of shape d1,d2. * {{{zeros((d1,d2),dtype)}}} returns array of shape d1,d2 filled with zeros * {{{ones((d1,d2),dtype)}}} returns array of shape d1,d2 filled with ones * {{{array(object,dtype)}}} returns an array from an object, e.g. a list * {{{dtype}}} fundamental C data type e.g. uint8, int16, int64, float32, float64 === Array indexing === * {{{A[y,x]}}} returns (y,x) element of the array * {{{A[:,x]}}} returns all elements of the y-dimension at x * {{{A[y1:y2,x]}}} * {{{A[:,:]}}} returns a copy of two dimensional array A * {{{A[:,:,0]}}} returns the first sub-image of a 3-dimensional array = Functions = == Function with one argument == {{{ In [124]: def quadrat(x): .....: return x**2 .....: In [125]: quadrat(2) Out[125]: 4 }}} == Function with variable number of arguments == {{{ In [126]: def printargs(*args): .....: for arg in args: .....: print arg .....: In [127]: printargs(a) [1, 2, 3] In [128]: printargs(a,range(4)) [1, 2, 3] [0, 1, 2, 3] }}} == Function with variable number of keywords == {{{ In [131]: def printkeys(**kw): .....: for k in kw.keys(): .....: print k,kw[k] .....: In [132]: printkeys(key1=10,key2='Hallo') key2 Hallo key1 10 }}} == Function with functions as arguments (expert) == Functions can be passed to functions as arguments. {{{#!python from scipy import sin,pi def func(x,f): return f(x) print func(pi/2,sin) }}} === eval(), apply() === In Matlab or IDL the passing of functions to functions works only with a detour using {{{feval()}}} or {{{Call_function()}}} * [[http://groups.google.com/group/comp.lang.idl-pvwave/browse_thread/thread/acf94d8f621caf95/47decec322cf5094?q=function+parameters&rnum=4|IDL passing functions to functions]] Of course, this way is possible in Python as well using the {{{eval()}}} or {{{apply()}}} function. {{{#!python apply(sin,(pi/2,)) f='sin' x=pi/2.0 eval(f+'('+str(x)+')') }}} In Fortran it is also possible to pass functions as arguments but with quite some overhead: * http://wingolog.org/software/fortran/tips-tricks.html = Lambda expressions (expert) = Lambda expressions are (anonymous) one line functions {{{#!python l=lambda x: x**2-1 l(4) }}} = Mapping (expert) = Similar as {{{apply()}}} works with one argument one can call {{{map()}}} with a sequence {{{#!python map(len,['Always','look','on','the','bright','side','of','life']) [6, 4, 2, 3, 6, 4, 2, 4] }}} The following example shows the combined usage of a lambda expression {{{#!python map(lambda s:len(s)+1,['Always','look','on','the','bright','side','of','life']) [7, 5, 3, 4, 7, 5, 3, 5] }}} = Variable Scope (expert) = The scope of an identifier refers to the variable visibility. Variables inside a function have a local scope. Global variables can be declared and used but you should be very careful. {{{#!python def bad_style(x): # Name space of bad_style global y y=x z=x return x # Name space of __main__ x,y,z=2,2,2 x=bad_style(1) print 'x=',x,'y=',y,'z=',z # y is changed! }}} = A shell inside the shell (expert) = For debugging purposes it is sometimes useful to investigate local variables at some points. The following example demonstrates a feature of ipython: {{{#!python from IPython.Shell import IPShellEmbed ips=IPShellEmbed() def spam(a): b=a+' Spam!' ips() print b }}} {{{ In [1]: from spam import spam In [2]: whos Interactive namespace is empty. In [3]: spam('Hello') # Now we are in the ips() call In [1]: whos Variable Type Data/Info ---------------------------- a str Hello b str Hello Spam! In [2]: exit() Do you really want to exit ([y]/n)? y Hello Spam! # We are now again in top level In [4]: whos Interactive namespace is empty. }}}